You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 引用).
#React 关于 setState() 使用不当产生的 warning
写 react 的时候有时会遇到这样的警告:
这篇博文说到可以用
this.isMounted()
来判断组件是否挂载了再去决定是否 setState, 但同时也说到this.isMounted()
是 antipattern 的. 这样做虽然会消除这种警告, 但这么做违背了官方特意给出这种警告的目的, 并且这样的代码让人看着确实有点 smell. 因为你没有真正解决编码中的问题, 因为 you think you might be holding a reference after the component has unmounted(这句话没看太明白, 我认为是这个组件都注销了你还用this.isMounted()
中的 这个 this 引用).有这么几种处理方法:
_is Mounted
变量, 在componentDidMount
时设为true
, 在componentWillUnmount
时设为 false, 用这个变量去确认这个组件的 Mounted 状态而不是用this.isMounted()
. 额, 这种方法我觉得也有点 smell.setState()
的地方然后解决. 大部分出现这种警告的原因是因为用setState()
的时候加了一个回调, 当这个组件在从服务端获取到数据之前, 这个组件已经被注销了, 然后再获取到数据的时候, 才在这个已经注销的组件里调用了setState()
. 这个时候应该在componentWillUnmount
取消这个 callback(建议用 ES6 的 promise 取消 callback). 其实, 组件里的所有 callbacks 都应该在componentWillUnmount
里取消的.参考文章
The text was updated successfully, but these errors were encountered: