index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, b

在React開發中,咱們可能常常會遇到這個一個警告:react

 

 咱們不能在組件銷燬後設置state,防止出現內存泄漏的狀況:ajax

 

關於react中切換路由時報以上錯誤,實際的緣由是由於在組件掛載(mounted)以後進行了異步操做,好比ajax請求或者設置了定時器等,而你在callback中進行了setState操做。當你切換路由時,組件已經被卸載(unmounted)了,此時異步操做中callback還在執行,所以setState沒有獲得值。異步

解決的方式有兩種:this

1、在卸載的時候對全部的操做進行清除(例如:abort你的ajax請求或者清除定時器)spa

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、設置一個flag,當unmount的時候重置這個flagcode

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

3、最簡單的方式(萬金油)component

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

4、在組件已經卸載時return,不去設置state:使用react組件this裏面的updater屬性上的isMounted方法判斷組件是否存在,若是不存在,就return,再也不去設置setState。blog

if (this.updater.isMounted(this)) {
     this.setState({
         dashBoardDate: otherDashBoardDate
    })   
} else {
    return
}
相關文章
相關標籤/搜索