react报错:Can‘t perform a React state update on an unmounted component

In React development, 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 the state after the component is destroyed to prevent memory leaks

Regarding the above error when switching routing in React, the actual reason is that asynchronous operations are performed after the component is mounted, such as an ajax request or a timer set, and you have performed a setState operation in the callback. When you switch the route, the component has been unmounted (unmounted), and the callback is still being executed in the asynchronous operation, so setState does not get a value.

There are two solutions:

1. Clear all operations when uninstalling (for example: abort your ajax request or clear the timer)

componentDidMount = () => {
    
    
    //1.ajax请求
    $.ajax('你的请求',{
    
    })
        .then(res => {
    
    
            this.setState({
    
    
                aa:true
            })
        })
        .catch(err => {
    
    })
    //2.定时器
    timer = setTimeout(() => {
    
    
        //dosomething
    },1000)
}
componentWillUnMount = () => {
    
    
    //1.ajax请求
    $.ajax.abort()
    //2.定时器
    clearTimeout(timer)
}

2. Set a flag, reset this flag when unmount

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

There is another way

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

Guess you like

Origin blog.csdn.net/Ruffaim/article/details/113829544
Recommended