Why does this error exist: “Invariant Violation: Cannot update during an existing state transition”

后端 未结 2 1821
难免孤独
难免孤独 2021-01-11 11:08

I seem to be running into this error in a large application (but I\'m not exactly sure where):

Uncaught Error: Invariant Violation: setState(...): Can

相关标签:
2条回答
  • 2021-01-11 11:20

    The issue is that setState will cause a re-render (potentially, depending on shouldComponentUpdate). If you had a setState call within the render function, it would trigger yet another render. You'd likely end up in an infinite loop of re-renderings. There's nothing that stops you from using setState as a result of some asynchronous operation (in fact it's very common). It's fine just as long as it's not in the render or some other lifecycle method of a component that is run on a state update (shouldComponentUpdate being another as you'd end up with an infinite loop in the same way).

    0 讨论(0)
  • 2021-01-11 11:46

    One way to achieve this is to use the Flux pattern and have your timeouts trigger changes in a store. This will cause the changes to propagate to interested components as part of their lifecycle.

    0 讨论(0)
提交回复
热议问题