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 the componentWillUnmount method.
当我们点击组件A后,组件A需要3秒的时间才能获取到数据并重新更新num的值,假如我们在这3秒内点击一次组件B,
表示卸载组件A,但是组件A的数据请求依然还在,当请求成功后,组件A已经不存在,此时就会报这个警告(大概意思就是:你组件都没了,你还设置个啥)
原因:本问题出现的原因就是:我们应该在组件销毁的时候将异步请求撤销
class组件
componentWillUnmount() {
this.setState = (state, callback) => {
return;
}
}
函数组件
// 省略组件其他内容,只列出 diff
useEffect(() => {
let isUnmounted = false;
(async () => { //异步请求
const res = await fetch(SOME_API);
const data = await res.json();
if (!isUnmounted) {
setValue(data.value);
setLoading(false);
}
})();
return () => {
isUnmounted = true;
}
}, []);
复制代码