[Solved] react Error: Can‘t perform a React state update on an unmounted component

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indic

In the development of react, we may often encounter 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.

We cannot set state after the component is destroyed to prevent memory leakage

As for the above errors when switching routes in react, the actual reason is that after the component is mounted, you perform asynchronous operations, such as Ajax requests or setting timers, and you perform setstate operation in callback. When you switch routes, the component has been unmounted. At this time, the callback is still executing in the asynchronous operation, so the setstate does not get a value.

There are two solutions:

1. Clear all operations when uninstalling (e.g. abort your Ajax request or clear timer)

componentDidMount = () => {
    //1.ajax request
    $.ajax('Your request',{})
        .then(res => {
            this.setState({
                aa:true
            })
        })
        .catch(err => {})
    //2.timer
    timer = setTimeout(() => {
        //dosomething
    },1000)
}
componentWillUnMount = () => {
    //1.ajax request
    $.ajax.abort()
    //2.timer
    clearTimeout(timer)
}

2. Set a flag and reset it when unmount

componentDidMount = () => {
    this._isMounted = true;
    $.ajax('Your Request',{})
        .then(res => {
            if(this._isMounted){
                this.setState({
                    aa:true
                })
            }
        })
        .catch(err => {})
}
componentWillUnMount = () => {
    this._isMounted = false;
}

3. The simplest way (oil of gold)

componentDidMount = () => {
    $.ajax('Your Request',{})
    .then(res => {
        this.setState({
            data: datas,
        });
    })
    .catch(error => {
 
     });
}
componentWillUnmount = () => {
    this.setState = (state,callback)=>{
      return;
    };
}

Read More: