【发布时间】:2020-10-28 23:10:34
【问题描述】:
我正在使用 Redux 在 React 中工作。我已经编写了名为 products 的操作,以使用 Axios 从后端获取产品详细信息。其中,如果用户在此过程中导航到另一个页面,我使用取消令牌来取消 HTTP 请求。
但是,当我导航到另一个页面时,我仍然在控制台中收到如下错误。
index.js:1 Warning: 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 a useEffect cleanup function.
当我导航到同一产品页面以获取数据时,请求会转到 catch 块以引发错误。我使用下面的代码来调度操作。
product.js 作为操作
const source = Axios.CancelToken.source();
const fetchProducts = () => {
return async (dispatch) => {
try {
const response = await Axios.get("myurl", {
cancelToken: source.token,
});
if (response.status !== 200) {
throw new Error("Something went wrong, while fetching the products!");
}
dispatch({ type: GET_PRODUCTS, products: response.data });
} catch (err) {
if (Axios.isCancel(err)) {
console.log(err.message);
} else {
throw err;
}
}
};
};
const cancelRequest = () => {
return (dispatch) => {
if (source !== typeof undefined) {
source.cancel("Operation canceled by the user.");
dispatch({ type: CANCEL_REQUEST, message: "Request canceled by user!" });
}
};
};
组件文件:
const loadProducts = useCallback(async () => {
setError(null);
try {
await dispatch(productActions.fetchProducts());
} catch (err) {
setError(err.message);
}
}, [dispatch, setError]);
useEffect(() => {
setIsLoading(true);
loadProducts().then(() => {
setIsLoading(false);
});
return () => {
dispatch(productActions.cancelRequest());
};
}, [dispatch, loadProducts, setIsLoading]);
如何解决这个问题?
【问题讨论】:
标签: reactjs react-redux axios