报错: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.
1.类组件就是用生命周期的勾子取取消掉订阅
componentDidMount = () => {
this.mounted = true;
}
componentWillUnMount = () => {
this.mounted = false;
}
2.函数组件
比如
const [aa, setAa] = useState(12);
useEffect(() => {
let mounted = true;
setTimeout(()=>{
if (!mounted) return; //2秒内组建被卸载,2秒之后再去setAa就报错;异步请求也是一样道理
setAa(23)
}, 2000)
// return就表示组件被卸载,比如切换路由
return () => {
mounted = false;
};
}, []);
也可以用const xxx = useRef(); xxx.mount = true,然后 xxx.mount && setAa(23),就是xxx.mount为true再去setState
其他方式原理一样
总结:就是setState必须是在组件没有被卸载之前可以设置,如果被卸载(如切换路由等),再去设置就会报错,常见于异步请求回来之后setState