如果您执行更新 componentWillMount
中的状态的异步操作(如文档所述),但在异步调用完成之前组件已卸载(用户导航离开),您最终会异步回调试图在一个现在未安装的组件上设置状态,一个
"Invariant Violation: replaceState(...): Can only update a mounted or mounting component."
错误。
解决这个问题的最佳方法是什么?
谢谢。
最佳答案
您可以使用 component.isMounted
方法在替换组件状态之前检查组件是否实际附加到 DOM。 Docs .
isMounted()
returnstrue
if the component is rendered into the DOM,false
otherwise. You can use this method to guard asynchronous calls tosetState()
orforceUpdate()
.
UPD:在你投反对票之前。这个答案是 2 年前给出的。这就是当时做事的方式。如果您刚刚开始使用 React,请不要遵循此答案。使用 componentDidMount
或您需要的任何其他生命周期 Hook 。
关于javascript - 异步设置 ReactJS 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25067364/