如何删除警告“无法对未安装的组件执行react状态更新”

IT技术 jquery ajax reactjs
2021-04-29 23:54:34

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

我已经设置了 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个回答

如果这是您正在构建的 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
}