This.setstate 在回调中卸载 [英] This.setstate unmounts within a callback

查看:42
本文介绍了This.setstate 在回调中卸载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里真的很困惑.我更新到需要一些更改的 React Router 4,现在当我的注册表在服务器端出错时,它返回控制台错误:

Really confused here. I updated to React Router 4 which required a few changes and now when my registration form errors on the server side it returns the console error:

setState(...):只能更新一个挂载或挂载的组件.这通常意味着您在未安装的组件上调用了 setState().这是无操作.请检查 RegisterForm 组件的代码.

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.

真正令人困惑的是,如果我在 Accounts.createUser 函数之外运行 this.setState({ errors: {createUserError: "Test error" }});没有得到控制台错误.

What's really confusing is if I run this.setState({ errors: {createUserError: "Test error" }}); outside of Accounts.createUser function I don't get the consolde error.

有什么建议吗????

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 }});
        }
      });
    });
  }

推荐答案

我认为在调用第二个 setState 之前卸载组件时可能会发生这种情况.也许 Accounts.createUser() 触发路由器导航或其他卸载组件的东西.

I assume this could happened when your component has been unmounted before your second setState is called. Maybe Accounts.createUser() triggers router navigation or something else that unmounts your component.

这篇关于This.setstate 在回调中卸载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆