From def5042e2b652db9a9f7d2da763ab86f30a75d48 Mon Sep 17 00:00:00 2001 From: Andrew Clark Date: Thu, 13 Apr 2023 23:44:29 -0400 Subject: [PATCH] Disable error recovery mechanism if infinite loop is detected If an infinite update loop is caused by a render phase update, the mechanism we typically use to break the loop doesn't work. Our mechanism assumes that by throwing inside `setState`, the error will caise the component to be unmounted, but that only works if the error happens in an effect or lifecycle method. During the render phase, what happens is that React will try to render the component one more time, synchronously, which we do as a way to recover from concurrent data races. But during this second attempt, the "Maximum update" error won't be thrown, because the counter was already reset. I considered a few different ways to fix this, like waiting to reset the counter until after the error has been surfaced. However, it's not obvious where this should happen. So instead the approach I landed on is to temporarily disable the error recovery mechanism. This is the same trick we use to prevent infinite ping loops when an uncached promise is passed to `use` during a sync render. This category of error is also covered by the more generic loop guard I added in the previous commit, but I also confirmed that this change alone fixes it. --- packages/react-reconciler/src/ReactFiberWorkLoop.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/react-reconciler/src/ReactFiberWorkLoop.js b/packages/react-reconciler/src/ReactFiberWorkLoop.js index 89781a4cfad26..ef31388f7f18a 100644 --- a/packages/react-reconciler/src/ReactFiberWorkLoop.js +++ b/packages/react-reconciler/src/ReactFiberWorkLoop.js @@ -3463,6 +3463,17 @@ export function throwIfInfiniteUpdateLoopDetected() { rootWithNestedUpdates = null; rootWithPassiveNestedUpdates = null; + if (executionContext & RenderContext && workInProgressRoot !== null) { + // We're in the render phase. Disable the concurrent error recovery + // mechanism to ensure that the error we're about to throw gets handled. + // We need it to trigger the nearest error boundary so that the infinite + // update loop is broken. + workInProgressRoot.errorRecoveryDisabledLanes = mergeLanes( + workInProgressRoot.errorRecoveryDisabledLanes, + workInProgressRootRenderLanes, + ); + } + throw new Error( 'Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' +