2017-05-25 15 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成功返回,這將允許您在出現錯誤時在窗體上顯示消息。例如,您可以指出哪些字段無效。