react异常:异步事件在组件卸载后更新state 导致的错误

react 异常:异步事件在组件卸载后更新 state 导致的错误

报错如下

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.

原因

异步事件在组件卸载后更新 state 导致的错误。

react 组件已经被销毁,而此时我们的异步操作(通常为调用接口更改 state 操作)还未结束。当我们的异步执行完成后要执行 setState 操作时,已经无法获得组件信息,由此造成该异常!

解决方案

我们应该在组件中通过 componentWillUnmount 钩子函数在组件销毁的时候将异步方法撤销:

1
2
3
4
5
6
7
8
9
10
11
componentWillUnmount() {
this.setState = () =>false;
}


// 函数组件,setState需let定义
useEffect(() => {
return () => {
setState = () => undefined;
};
}, []);

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!