Skip to content

Commit

Permalink
Disable error recovery mechanism if infinite loop is detected
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
acdlite committed Apr 14, 2023
1 parent 43bfd09 commit def5042
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/react-reconciler/src/ReactFiberWorkLoop.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ' +
Expand Down

0 comments on commit def5042

Please sign in to comment.