首页 > 解决方案 > 如何解决 ReactJs Can't perform a React state update on an unmounted component

问题描述

当我尝试使用反应路由器时出现此错误,我注意到在我的 reactjs 环境中一切正常,但是当我运行 npm run build file 时反应路由器不起作用,

这是完整的错误,我看到我的控制台需要修复它。

index.js: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.
    in TextTypeEffect (at carousel.js:8)
    in div (at carousel.js:7)
    in div (at carousel.js:6)
    in Carousel (at App.js:71)
    in Home (at App.js:41)

标签: reactjsreact-router

解决方案


当您的组件在组件卸载后尝试设置状态时会发生这种情况,因此您需要取消订阅状态更新componentWillUnmount() 下面是类组件的示例代码

import React, { Component } from 'react';

class MyComponent extends Component {

    _isMounted = false;

    componentDidMount() {
        this._isMounted = true;
    }

    componentWillUnmount = () => this._isMounted = false;

    setState = (state, callback) => this._isMounted && super.setState(state, callback);
}

推荐阅读