Can’t perform a React state update on an unmounted component

栏目: 服务器 · 发布时间: 6年前

导语: 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 t

最近项目中有一个这样的需求,从别的项目要转到我项目中的某个页面,不过回退时要可以回退到项目的首页。

实现这样的跳转的话,应当是首先要跳转到项目的首页,然后再从首页跳转到对应的页面。

我最开始的实现是这样的:

componentDidMount() {
    const jumpUrlList = ['own'];
    const jumpUrl = getQueryString('jumpto');
    const targetJump = window.sessionStorage && window.sessionStorage.getItem('targetJump');

    // 防止无限跳转,使用sessionStorage存储一个标记,整个周期内只跳转一次
    if (jumpUrlList.indexOf(jumpUrl) > -1 && !targetJump) {
        window.location.href = '#/' + jumpUrl;
        window.sessionStorage.setItem('targetJump', '1');
    }
}

但运行时,会提示这个错误:

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.

意思是:无法对没有实例的组件进行响应状态更新。您可以在 componentWillUnmount 方法中取消所有的订阅和异步任务。

因为我在首页中有异步请求,请求返回回来后,使用 setState 更新视图。但我已经跳转到别的路由了,导致 setState 更新时,当前组件已被销毁了,无法更新。

解决方法:

  1. 若您的异步请求可以取消的话,在 componentWillUnmount 中取消请求;

  2. render() 方法中进行判断,若可以跳转,则直接不渲染;

render() {
    const jumpUrlList = ['own'];
    const jumpUrl = getQueryString('jumpto');
    const targetJump = window.sessionStorage && window.sessionStorage.getItem('targetJump');
    if (jumpUrlList.indexOf(jumpUrl) > -1 && !targetJump) {
        window.location.href = '#/' + jumpUrl;
        window.sessionStorage.setItem('targetJump', '1');
        return null;
    }

    return (
        <div className="home">
            <User />
        </div>
    );
}
  1. 使用高阶组件重新封装 componentWillUnmount 和 setState;

function inject_unount(target) {
    // 改装componentWillUnmount,销毁的时候记录一下
    let next = target.prototype.componentWillUnmount;
    target.prototype.componentWillUnmount = function() {
        if (next) next.call(this, ...arguments);
        this.unmount = true;
    };
    // 对setState的改装,setState查看目前是否已经销毁
    let setState = target.prototype.setState;
    target.prototype.setState = function() {
        if (this.unmount) return;
        setState.call(this, ...arguments);
    };
}
@inject_unount
class BaseComponent extends Component {}
//以后我们写组件时直接继承BaseComponent

@2019-06-03 18:03 评论(0)


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

三位一体

三位一体

[美]迈克尔·马隆 / 黄亚昌 / 浙江人民出版社 / 2015-4 / 98.90

[内容简介] ●本书讲述了罗伯特•诺伊斯、戈登•摩尔和安德鲁•格鲁夫如何缔造了世界上最重要公司的故事。公司的“外交家”诺伊斯被视为圣父、“思想家”摩尔被视为圣灵、“行动家”格鲁夫被视为圣子,这个三位一体的组合创下了企业管理中的奇迹,开创了一个价值万亿美元的产业,将一家初创企业打造成为千亿美元量级的巨型公司。 ●本书作者迈克尔•马隆在接触空前数量的企业档案的基础上,揭示了英特尔公司无处不......一起来看看 《三位一体》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具