React - setState() on unmounted component

Marty picture Marty · Oct 2, 2015 · Viewed 91.4k times · Source

In my react component im trying to implement a simple spinner while an ajax request is in progress - im using state to store the loading status.

For some reason this piece of code below in my React component throws this error

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

If I get rid of the first setState call the error goes away.

The question is why am I getting this error when the component should already be mounted (as its being called from componentDidMount) I thought it was safe to set state once the component is mounted ?

Answer

Bruno Mota picture Bruno Mota · Oct 2, 2015

Without seeing the render function is a bit tough. Although can already spot something you should do, every time you use an interval you got to clear it on unmount. So:

componentDidMount() {
    this.loadInterval = setInterval(this.loadSearches, this.props.pollInterval);
}

componentWillUnmount () {
    this.loadInterval && clearInterval(this.loadInterval);
    this.loadInterval = false;
}

Since those success and error callbacks might still get called after unmount, you can use the interval variable to check if it's mounted.

this.loadInterval && this.setState({
    loading: false
});

Hope this helps, provide the render function if this doesn't do the job.

Cheers