Tag Archives: ReactNative

[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();
  };
}