【发布时间】:2020-01-29 15:20:32
【问题描述】:
在我的 React 组件中,我有一个 async 请求,它向我的 Redux 存储分派一个操作,该存储在 useEffect 钩子中调用:
const loadFields = async () => {
setIsLoading(true);
try {
await dispatch(fieldsActions.fetchFields(user.client.id));
} catch (error) {
setHasError(true);
}
setIsLoading(false);
}
useEffect(() => { if(isOnline) { loadFields() } }, [dispatch, isOnline]);
动作通过获取请求请求数据:
export const fetchFields = clientId => {
return async dispatch => {
try {
const response = await fetch(
Api.baseUrl + clientId + '/fields',
{ headers: { 'Apiauthorization': Api.token } }
);
if (!response.ok) {
throw new Error('Something went wrong!');
}
const resData = await response.json();
dispatch({ type: SET_FIELDS, payload: resData.data });
} catch (error) {
throw error;
}
}
};
export const setFields = fields => ({
type : SET_FIELDS,
payload : fields
});
当它在 React 应用程序中呈现时,会导致以下警告:
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function
我相信这是因为 Promise 没有“清理”功能。但我不确定在哪里放置这个?我应该在LoadFields() 中有一些逻辑吗?还是必须在 useEffect 挂钩内完成?
【问题讨论】:
-
您的问题是否重复? stackoverflow.com/questions/38329209/…
-
并非如此,因为这个使用的是 react-hooks + http 调用本身没有问题
-
@chin8628 我同意@oktapodia 的观点,因为这个问题也特别与 axios 有关。我的问题是理解删除
useEffect中的订阅作为async函数的一部分。
标签: javascript reactjs promise