I tried to set my state, but it returns "Can't call setState on a component that is not yet mounted." error

Viewed 50
class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      frontURL: null,
      backURL: null,
    };
  }

viewApplicant = (e) => {
    var driverID = e.target.parentElement.parentElement.id;

    firebase.storage()
      .ref("license/" + driverID)
      .child("front")
      .getDownloadURL()
      .then(frontURL => {
        this.setState({
          frontURL
        });
      }).catch(() => {
        alert('Front image could not be loaded')
      });


    firebase.storage()
      .ref("license/" + driverID)
      .child("back")
      .getDownloadURL()
      .then(backURL => {
        this.setState({
          backURL
        });
      }).catch(() => {
        alert('Back image could not be loaded')
      });
  }
}

I'm trying to get my image from Firebase storage, I am able to get the image URL but when I try to set my state to that of the URL, the warning message returned in the console always says that my component is not mounted, which I do not understand because from my understanding, a component has to be mounted to be able to render. and cause of this, my image is not displayed.

I am new to React and any explanation of why this is happening would be much appreciated.

I have checked against previous posts about this,

  • I do not have react-hot-loader installed
  • I have initialized my states in the constructor
  • I have checked that my component is mounted through componentDidMount
1 Answers

I think you should use a variable _isMounted to check when your component is mounted. Read more at: https://www.robinwieruch.de/react-warning-cant-call-setstate-on-an-unmounted-component

class Dashboard extends React.Component {
  _isMounted = false;
  constructor(props) {
    super(props);
    this.state = {
      frontURL: null,
      backURL: null,
    };
  }

  componentDidMount() {
    this._isMounted = true;

    firebase.storage()
      .ref("license/" + driverID)
      .child("front")
      .getDownloadURL()
      .then(frontURL => {
        if (_isMounted) {
          this.setState({
          frontURL
        });
        }
      }).catch(() => {
        alert('Front image could not be loaded')
      });
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  ....
}
Related