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

React Common Component Issues: Can’t perform a React state update on an unmounted component [How to Solve]

In some react components, there will be this 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”

This is because after writing a method to complete the request, we change the state

  payload:values,
        callback:res=>{
          if(res.code === 0){
            notification.success({
              message: 'Password updated successfully',
              description: `The new password is ${res.data}`,
              duration: 0,
            });
            successed&& successed();
              that.setState({
                updatePwdModalVisible:false
              })
            that.getCaptcha();

Solution: using the life cycle hook function: component will unmount, clear the timer before the component is unloaded

that.pwdErrorTimer = setTimeout(() => {
              this.setState({
                updatePwdModalVisible:false
              })
            }, 1000);
componentWillUnmount(){
    clearTimeout(this.pwdErrorTimer);
  }

[Solved] ReactNative Warning: Can’t perform a React state update on an unmounted component

This error is obvious, because when the component is destroyed, people use the method of setstate, but there is no such method as weak in OC/swift in RN, here is a method to solve this error:

import React,{PureComponent} from 'react';

function inject_unount(Target){
  // Retrofit componentWillUnmount, record when destroyed (when used by subclasses, super is required)
  var next = Target.prototype.componentWillUnmount;
  Target.prototype.componentWillUnmount = function() {
    if (next) {
      next.call(this, ...arguments);
    }
    this.unmount = true;
  };
  // Modifications to setState, setState to see if it is currently destroyed
  let setState = Target.prototype.setState;
  Target.prototype.setState = function() {
    // if (this.unmount) {
    //   return;
    // }
    setState.call(this, ...arguments);
  };
}

@inject_unount
export default class BaseComponent extends PureComponent {}

Other components inherit from basecomponent

import BaseComponent from 'xxx';

export default class HZJDemo extends BaseComponent {
  //If you override this method, remember to super
  componentWillUnmount = () => {
    super.componentWillUnmount();
  };
}