2017-05-25 69 views
3

真的很困惑这里。我更新了React Router 4,它需要进行一些更改,现在当我的注册在服务器端出现错误时,它返回控制台错误: 这是回调。如何停止从卸载组件回调

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the RegisterForm component.

什么是真正的困惑是,如果我跑this.setState({ errors: {createUserError: "Test error" }});Accounts.createUser功能我没有得到consolde错误。

任何建议????

handleSubmit(event) { 
    event.preventDefault(); 

    this.setState({errors: {} }, function() { 
     var data = { 
     email: this.state.email, 
     password: this.state.password 
     }; 

     Accounts.createUser(data, (error) => { // This arrow function preserves this 
     if(error) { 
      this.setState({ errors: {createUserError: error.reason }}); 
     } 
     }); 
    }); 
    } 
+0

[This.setstate在回调中卸载]的副本(https://stackoverflow.com/questions/44150077/this-setstate-unmounts-within-a-callback)。请不要重复发布。 – MasterAM

回答

2

通过由Accounts.createUser生成的HTTP请求返回错误时,即handleSubmit被绑定到组件被卸载,这就是为什么呼叫setState生成错误。

一种选择是将handleSubmit移动到未在表单提交中卸载并将该函数作为道具传递的父项。另一种选择是使用redux或flux来进行状态管理。

另一种选择是保持组件安装到Accounts.createUser成功返回,这将允许您在出现错误时在窗体上显示消息。例如,您可以指出哪些字段无效。