I seem to be running into this error in a large application (but I'm not exactly sure where):
Uncaught Error: Invariant Violation: setState(...): Cannot update
during an existing state transition (such as within render
). Render
methods should be a pure function of props and state.
I suspect it might be the result of using setState
inside of setTimeout
or setInterval
.
Which leads me to my real question: why does this error exist? Is there some conceptual reason I'm missing why ReactJS doesn't just queue state and prop changes? I'm guessing if there is a reason, it has to do with application complexity and/or avoiding race conditions...
My next question then would be: what is the proper way to update a component outside of React (during some asynchronous event for example) so that this error doesn't occur?
Edit:
After some digging into this issue further, it appears the culprit is actually the underlying platform I'm using (ElectronJS, formally Atom Shell). Basically, ElectronJS combines Chromium and NodeJS together. I was using a NodeJS API to do something asynchronous and it appears when that finished, ElectronJS would just return back to the call stack where it left off, bypassing the event loop altogether and thus causing a race condition with React.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…