关于React抛出异常,Can‘t perform a React state update on an unmounted component.错误的解决方案【已解决】

33 篇文章 0 订阅
7 篇文章 4 订阅

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.
错误含义:警告:无法对未挂载的组件执行React状态更新。这是一个无操作,但它表明应用程序中存在内存泄漏。要修复此问题,请取消componentWillUnmount方法中的所有订阅和异步任务。


问题描述

在进行页面切换时,如果页面中存在异步执行操作 setState 或其他操作时,在未执行完成即进行页面切换(此时 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 the componentWillUnmount method.
    in ActivityIndex (created by LoadableComponent)
    in LoadableComponent (created by Context.Consumer)
    in Route (at Content/index.jsx:43)
    in Switch (at Content/index.jsx:38)
    in Transition (created by CSSTransition)
    in CSSTransition (at Content/index.jsx:32)

原因分析

react 组件已经被销毁,而此时我们的异步操作(通常为调用接口后进行 setState 操作)还未结束。当我们的异步执行完成后要执行 setState 操作时,react 已经无法获得当前组件的信息,遂报出此错误。


解决方案

解决这个异常很简单,我们只要清楚了为什么会抛出此异常,便可轻松解决。

我们需要在组件中通过 componentWillUnmount 钩子函数在组件销毁的时候将此异步方法撤销即可。

componentWillUnmount() {
    this.setState = () => false;
}

再运行程序,随便切换页面,不再会出现此报错信息。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值