Javascript 未捕获不变冲突:超过最大更新深度

Javascript 未捕获不变冲突:超过最大更新深度,javascript,reactjs,Javascript,Reactjs,我试图在函数完成后设置状态,但出现错误: Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infini

我试图在函数完成后设置状态,但出现错误:

Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. 
在函数完成后,我在回调中调用setstate,因此我认为从我所读的内容来看,这可以正常工作,但我似乎无法使其工作

在组件更新时运行函数addStuff

componentDidUpdate() {
   this.addStuff(() => this.setState({"loading":false}))
}
完成时设置回调

addStuff(callback) {
    ...Does a bunch of stuff
    callback();
}

有人能告诉我我做错了什么吗?谢谢。

如果您阅读,它会清除状态“您可以在componentDidUpdate()中立即调用setState(),但请注意,它必须包装在上面示例中的条件中,否则将导致无限循环。”因此,对于您的函数来说,这与正在发生的事情是一样的。

无限循环的原因是您没有将
设置状态
包装在条件中,而是包装在回调中

所以我认为只要组件更新,就会调用
setState
,这会触发重新渲染,这意味着调用
componentdiddupdate
,这会设置状态,这会触发重新渲染,这会调用
componentdiddupdate
,等等

这就是为什么
componentdiddupdate
中的设置状态应始终为有条件的原因,如中所述。在您的情况下,可能看起来像这样,您比较相关的道具,以验证您确实需要重新播放:

componentDidUpdate(prevProps) {
  if (this.props.relevantProp!== prevProps.relevantProp) {
    this.addStuff(() => this.setState({"loading":false}))
  }
}

否默认情况下在应用程序状态中为true可能重复