Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 setState() 使用不当产生的 warning #9

Open
wuzhenquan opened this issue Apr 7, 2017 · 0 comments
Open

关于 setState() 使用不当产生的 warning #9

wuzhenquan opened this issue Apr 7, 2017 · 0 comments
Labels

Comments

@wuzhenquan
Copy link
Owner

wuzhenquan commented Apr 7, 2017

#React 关于 setState() 使用不当产生的 warning

写 react 的时候有时会遇到这样的警告:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.

这篇博文说到可以用 this.isMounted()来判断组件是否挂载了再去决定是否 setState, 但同时也说到 this.isMounted() 是 antipattern 的. 这样做虽然会消除这种警告, 但这么做违背了官方特意给出这种警告的目的, 并且这样的代码让人看着确实有点 smell. 因为你没有真正解决编码中的问题, 因为 you think you might be holding a reference after the component has unmounted(这句话没看太明白, 我认为是这个组件都注销了你还用 this.isMounted()中的 这个 this 引用).

有这么几种处理方法:

  • 一种办法是你自己去跟踪这个组件的 mounted 状态. 用一个 _is Mounted 变量, 在 componentDidMount 时设为 true, 在 componentWillUnmount 时设为 false, 用这个变量去确认这个组件的 Mounted 状态而不是用 this.isMounted(). 额, 这种方法我觉得也有点 smell.
  • 一种办法是找到这个组件注销时还在用 setState() 的地方然后解决. 大部分出现这种警告的原因是因为用 setState() 的时候加了一个回调, 当这个组件在从服务端获取到数据之前, 这个组件已经被注销了, 然后再获取到数据的时候, 才在这个已经注销的组件里调用了 setState(). 这个时候应该在 componentWillUnmount 取消这个 callback(建议用 ES6 的 promise 取消 callback). 其实, 组件里的所有 callbacks 都应该在 componentWillUnmount 里取消的.

参考文章

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant