[英]Can't perform a React state update on an unmounted component with useEffect hook
I have我有
useEffect(() => {
setLoading(true);
axios
.get(url, {params})
.then(data => {
setData(data || []);
setLoading(false);
})
.catch(() => {
showToast('Load data failed!', 'error');
setLoading(false);
});
}, [params]);
It gives me它给了我
Warning: Can't perform a React state update on an unmounted component.
警告:无法对未安装的组件执行 React state 更新。 This is a no-op, but it indicates a memory leak in your application.
这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。 To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
要修复此问题,请在 useEffect 清理 function 中取消所有订阅和异步任务。
Ok, the question IS NOT HOW TO SOLVE IT.好的,问题不在于如何解决。 When I use setLoading(false) after
axios
promise it works fine but inside of promise (eg above) it always gives me warning.当我在
axios
promise 之后使用 setLoading(false) 时,它工作正常,但在 promise 内部(例如上面)它总是给我警告。 Actually I want to know WHY IT HAPPENS SO?其实我想知道为什么会这样? Is there anybody who may explain me in a nutshell a flow of code above (the process how code above works with warning) and maybe give some best practices on using hooks.
有没有人可以简单地向我解释上面的代码流(上面的代码如何与警告一起工作的过程),并可能给出一些使用钩子的最佳实践。
you need clean up function.你需要清理 function。 this means you should call function end of useEffect function.
这意味着您应该调用 function end of useEffect function。 when dependencie is changes (params as your example ) calls that function.
当依赖项发生变化时(以参数为例)调用 function。 so we would be able controll when component mounts/unmounts
所以我们可以控制组件何时挂载/卸载
useEffect(() => {
let cancelled = false;
setLoading(false);
async function fetchData() {
try {
const response = await axios.get(url, { params });
if (!cancelled) {
setData(response.data);
setLoading(false);
}
} catch (e) {
if (!cancelled) {
showToast(e.message, "error");
setLoading(false);
}
}
}
fetchData();
// clean up here
return () => {
cancelled = true;
};
}, [params]);
WHY IT HAPPENS SO?
为什么会这样?
Imagine your request is goes slow, and the component has already unmounted when the async request finishes.
想象一下,您的请求变慢了,并且当异步请求完成时组件已经卸载。 this time throws this warning
这次抛出这个警告
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.