React 组件销毁时清除订阅、定时器以及清理异步操作和取消请求等资源

问题

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.

警告:无法对未安装的组件执行 React 状态更新。 这是一个空操作,但它表明您的应用程序中存在内存泄漏。 要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。

解决办法:清除 effect

useEffect(() => {
  const subscription = props.source.subscribe();
  return () => {
    // 清除订阅
    subscription.unsubscribe();
  };
});

react 组件销毁时 清理异步操作和取消请求

在componetWillMount 中访问了接口返回数据后,调用了setState,访问的时候按了后退,导致还没收到响应就销毁了组件 ,但是fetch请求没被结束掉,之后收到响应就调用了setState(),发出如上所示警告。

原因:React中,因为异步操作的关系,组件销毁后调用了 setState();

使用 class 组件解决办法:

componentWillUnmount(){
        // 卸载异步操作设置状态
        this.setState = (state, callback) => {
            return;
        }
    }

————————————————
原文链接:https://blog.csdn.net/qq_44721831/article/details/123137841

posted on 2022-11-02 13:33  爱上键盘的蜗牛  阅读(633)  评论(0编辑  收藏  举报

导航