如何删除警告“无法在未安装的组件上执行反应状态更新”

时间:2018-12-31 20:05:41

标签: jquery ajax reactjs

我有一个身份验证系统,在该系统中,用户可以登录,如果经过身份验证,则将用户重定向到主页...它工作正常,但是唯一的问题是,它警告我无法更新已卸载组件上的状态我已经在互联网上尝试了与该问题相关的所有方法,但未能删除警告...

我已经设置了isMounted标志,并在componentDidMount中将其设置为true,但是并没有帮助。.我也尝试在componentWillUnMount中清除Interval和Timeout,但仍然失败...

login = () => {
  var mythis = this;
  var name = this.state.name;
  var  password = this.state.password
    this.setState({isLoading:true,show:true});
  this.interval = setInterval(function(){
    mythis.setState({show:true})
  },300);
  $.ajax({
    url : 'http://localhost:4000/login',
    type : "POST",
    data : {username:name,password:password},
    success : function(data){
    mythis.firstTimeout =  setTimeout(function(){
        clearInterval(mythis.interval);
      if(data == true){


    mythis.setState({show:false});
   mythis.secondTimeout=setTimeout(function(){

      mythis.setState({isLoading:false});

    },200)

      }
      else {

        mythis.setState({show:false});
        mythis.secondTimeout=setTimeout(function(){
          mythis.setState({isLoading:false})
        },200)
      }

    },2000)

    }.bind(this)
  })
}

componentWillUnMount(){
//this._isMounted = false;
clearInterval(this.interval);
clearTimeout(this.firstTimeout);
clearTimeout(this.secondTimeout);

}

render(){
return (
<div>
{this.state.isLoading ? (
        <div>
           <Loading
             show={this.state.show}
             color="red"
             showSpinner={false}
           />
           </div>
      ):''}
}
</div>
)

1 个答案:

答案 0 :(得分:4)

如果您正在构建一个React应用,请在componentDidMount生命周期方法中调用ajax请求。 首先设置您的私人变量     _isMounted=false

然后在componentDidMount中:

componentDidMount() {
    this._isMounted = true;
    .... your ajax request here
}

在您的ajax成功函数中:

if (this._isMounted) {
    this.setState({ isLoading: false });
   }

然后使用componentWillUnmount生命周期方法:

componentWillUnmount(){
  this._isMounted= false
}