简体   繁体   中英

Can't get rid of: Warning: Can't perform a React state update on an unmounted component

Full warning message: 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 a useEffect cleanup function.

This warning is NOT showing constant, it shows whenever it feels like. MOST TIMES when the app just started.

export default class something extends React.Component {
  _isMounted = false;
  state = {
    
  };

componentDidMount() {
    this._isMounted = true;
    firebase = new Fire((error, user) => {
      if (error) {
        return alert('something something something something');
      }

      firebase.getLists((lists) => {
        this.setState({ lists, user }, () => {
            this.setState({ loading: false });
        });
      });
      this.setState({ user });
    });
  }

componentWillUnmount() {
    this._isMounted = true;
    firebase.detach();
  }

this is in an another file that contains all the firebase code

detach() {
    this.unsubscribe();
  }

My guess it has to do with detach firebase.detach

There are a few minor updates that are needed in your code for it to work correctly.

You'll want to check if _isMounted is true before updating any state variables.

You'll also want to set _isMounted=false in componentWillUnmount() instead of _isMounted=true .

See the updated code below:

export default class something extends React.Component {
  _isMounted = false;
  state = {
    
  };

componentDidMount() {
    this._isMounted = true;
    firebase = new Fire((error, user) => {
      if (error) {
        return alert('something something something something');
      }

      firebase.getLists((lists) => {
        if (this._isMounted){
          this.setState({ lists, user }, () => {
            this.setState({ loading: false });
          });
        }
      });
      if (this._isMounted){
        this.setState({ user });
      }
    });
  }

componentWillUnmount() {
    this._isMounted = false;
    firebase.detach();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM