【问题标题】:how to remove the warning "can't perform a react state update on unMounted Component"如何删除警告“无法对未安装的组件执行反应状态更新”
【发布时间】:2019-01-13 15:49:28
【问题描述】:

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

我设置了 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>
)

【问题讨论】:

    标签: jquery ajax reactjs


    【解决方案1】:

    如果这是您正在构建的反应应用程序,您可以在 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
    }
    

    【讨论】:

    • 功能组件怎么样?
    • 在功能组件中实现 useEffect 钩子。并在该钩子中运行清理功能,设置 _isMounted =false ,从而模仿 componentWillUnmount
    猜你喜欢
    • 2021-02-24
    • 2020-03-20
    • 1970-01-01
    • 2021-11-09
    • 2021-08-05
    • 2021-03-27
    • 2021-04-11
    • 2019-09-11
    相关资源
    最近更新 更多