Skip to content

Commit 05865c3

Browse files
acdlitetyao1
authored andcommitted
Fix: Detect infinite update loops caused by render phase updates (facebook#26625)
This PR contains a regression test and two separate fixes: a targeted fix, and a more general one that's designed as a last-resort guard against these types of bugs (both bugs in app code and bugs in React). I confirmed that each of these fixes separately are sufficient to fix the regression test I added. We can't realistically detect all infinite update loop scenarios because they could be async; even a single microtask can foil our attempts to detect a cycle. But this improves our strategy for detecting the most common kind. See commit messages for more details.
1 parent ea8a861 commit 05865c3

File tree

4 files changed

+204
-13
lines changed

4 files changed

+204
-13
lines changed

packages/react-dom/src/__tests__/ReactUpdates-test.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1620,6 +1620,64 @@ describe('ReactUpdates', () => {
16201620
});
16211621
});
16221622

1623+
it("does not infinite loop if there's a synchronous render phase update on another component", () => {
1624+
let setState;
1625+
function App() {
1626+
const [, _setState] = React.useState(0);
1627+
setState = _setState;
1628+
return <Child />;
1629+
}
1630+
1631+
function Child(step) {
1632+
// This will cause an infinite update loop, and a warning in dev.
1633+
setState(n => n + 1);
1634+
return null;
1635+
}
1636+
1637+
const container = document.createElement('div');
1638+
const root = ReactDOMClient.createRoot(container);
1639+
1640+
expect(() => {
1641+
expect(() => ReactDOM.flushSync(() => root.render(<App />))).toThrow(
1642+
'Maximum update depth exceeded',
1643+
);
1644+
}).toErrorDev(
1645+
'Warning: Cannot update a component (`App`) while rendering a different component (`Child`)',
1646+
);
1647+
});
1648+
1649+
it("does not infinite loop if there's an async render phase update on another component", async () => {
1650+
let setState;
1651+
function App() {
1652+
const [, _setState] = React.useState(0);
1653+
setState = _setState;
1654+
return <Child />;
1655+
}
1656+
1657+
function Child(step) {
1658+
// This will cause an infinite update loop, and a warning in dev.
1659+
setState(n => n + 1);
1660+
return null;
1661+
}
1662+
1663+
const container = document.createElement('div');
1664+
const root = ReactDOMClient.createRoot(container);
1665+
1666+
await expect(async () => {
1667+
let error;
1668+
try {
1669+
await act(() => {
1670+
React.startTransition(() => root.render(<App />));
1671+
});
1672+
} catch (e) {
1673+
error = e;
1674+
}
1675+
expect(error.message).toMatch('Maximum update depth exceeded');
1676+
}).toErrorDev(
1677+
'Warning: Cannot update a component (`App`) while rendering a different component (`Child`)',
1678+
);
1679+
});
1680+
16231681
// TODO: Replace this branch with @gate pragmas
16241682
if (__DEV__) {
16251683
it('warns about a deferred infinite update loop with useEffect', async () => {

packages/react-reconciler/src/ReactFiberRootScheduler.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,18 @@ export function ensureRootIsScheduled(root: FiberRoot): void {
139139
}
140140
}
141141

142+
function unscheduleAllRoots() {
143+
// This is only done in a fatal error situation, as a last resort to prevent
144+
// an infinite render loop.
145+
let root = firstScheduledRoot;
146+
while (root !== null) {
147+
const next = root.next;
148+
root.next = null;
149+
root = next;
150+
}
151+
firstScheduledRoot = lastScheduledRoot = null;
152+
}
153+
142154
export function flushSyncWorkOnAllRoots() {
143155
// This is allowed to be called synchronously, but the caller should check
144156
// the execution context first.
@@ -166,10 +178,47 @@ function flushSyncWorkAcrossRoots_impl(onlyLegacy: boolean) {
166178

167179
// There may or may not be synchronous work scheduled. Let's check.
168180
let didPerformSomeWork;
181+
let nestedUpdatePasses = 0;
169182
let errors: Array<mixed> | null = null;
170183
isFlushingWork = true;
171184
do {
172185
didPerformSomeWork = false;
186+
187+
// This outer loop re-runs if performing sync work on a root spawns
188+
// additional sync work. If it happens too many times, it's very likely
189+
// caused by some sort of infinite update loop. We already have a loop guard
190+
// in place that will trigger an error on the n+1th update, but it's
191+
// possible for that error to get swallowed if the setState is called from
192+
// an unexpected place, like during the render phase. So as an added
193+
// precaution, we also use a guard here.
194+
//
195+
// Ideally, there should be no known way to trigger this synchronous loop.
196+
// It's really just here as a safety net.
197+
//
198+
// This limit is slightly larger than the one that throws inside setState,
199+
// because that one is preferable because it includes a componens stack.
200+
if (++nestedUpdatePasses > 60) {
201+
// This is a fatal error, so we'll unschedule all the roots.
202+
unscheduleAllRoots();
203+
// TODO: Change this error message to something different to distinguish
204+
// it from the one that is thrown from setState. Those are less fatal
205+
// because they usually will result in the bad component being unmounted,
206+
// and an error boundary being triggered, rather than us having to
207+
// forcibly stop the entire scheduler.
208+
const infiniteUpdateError = new Error(
209+
'Maximum update depth exceeded. This can happen when a component ' +
210+
'repeatedly calls setState inside componentWillUpdate or ' +
211+
'componentDidUpdate. React limits the number of nested updates to ' +
212+
'prevent infinite loops.',
213+
);
214+
if (errors === null) {
215+
errors = [infiniteUpdateError];
216+
} else {
217+
errors.push(infiniteUpdateError);
218+
}
219+
break;
220+
}
221+
173222
let root = firstScheduledRoot;
174223
while (root !== null) {
175224
if (onlyLegacy && root.tag !== LegacyRoot) {

packages/react-reconciler/src/ReactFiberWorkLoop.js

Lines changed: 88 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,9 @@ import {
142142
includesExpiredLane,
143143
getNextLanes,
144144
getLanesToRetrySynchronouslyOnError,
145-
markRootUpdated,
146-
markRootSuspended as markRootSuspended_dontCallThisOneDirectly,
147-
markRootPinged,
145+
markRootSuspended as _markRootSuspended,
146+
markRootUpdated as _markRootUpdated,
147+
markRootPinged as _markRootPinged,
148148
markRootEntangled,
149149
markRootFinished,
150150
addFiberToLanesMap,
@@ -373,6 +373,13 @@ let workInProgressRootConcurrentErrors: Array<CapturedValue<mixed>> | null =
373373
let workInProgressRootRecoverableErrors: Array<CapturedValue<mixed>> | null =
374374
null;
375375

376+
// Tracks when an update occurs during the render phase.
377+
let workInProgressRootDidIncludeRecursiveRenderUpdate: boolean = false;
378+
// Thacks when an update occurs during the commit phase. It's a separate
379+
// variable from the one for renders because the commit phase may run
380+
// concurrently to a render phase.
381+
let didIncludeCommitPhaseUpdate: boolean = false;
382+
376383
// The most recent time we either committed a fallback, or when a fallback was
377384
// filled in with the resolved UI. This lets us throttle the appearance of new
378385
// content as it streams in, to minimize jank.
@@ -1095,6 +1102,7 @@ function finishConcurrentRender(
10951102
root,
10961103
workInProgressRootRecoverableErrors,
10971104
workInProgressTransitions,
1105+
workInProgressRootDidIncludeRecursiveRenderUpdate,
10981106
);
10991107
} else {
11001108
if (
@@ -1129,6 +1137,7 @@ function finishConcurrentRender(
11291137
finishedWork,
11301138
workInProgressRootRecoverableErrors,
11311139
workInProgressTransitions,
1140+
workInProgressRootDidIncludeRecursiveRenderUpdate,
11321141
lanes,
11331142
),
11341143
msUntilTimeout,
@@ -1141,6 +1150,7 @@ function finishConcurrentRender(
11411150
finishedWork,
11421151
workInProgressRootRecoverableErrors,
11431152
workInProgressTransitions,
1153+
workInProgressRootDidIncludeRecursiveRenderUpdate,
11441154
lanes,
11451155
);
11461156
}
@@ -1151,6 +1161,7 @@ function commitRootWhenReady(
11511161
finishedWork: Fiber,
11521162
recoverableErrors: Array<CapturedValue<mixed>> | null,
11531163
transitions: Array<Transition> | null,
1164+
didIncludeRenderPhaseUpdate: boolean,
11541165
lanes: Lanes,
11551166
) {
11561167
// TODO: Combine retry throttling with Suspensey commits. Right now they run
@@ -1177,15 +1188,21 @@ function commitRootWhenReady(
11771188
// us that it's ready. This will be canceled if we start work on the
11781189
// root again.
11791190
root.cancelPendingCommit = schedulePendingCommit(
1180-
commitRoot.bind(null, root, recoverableErrors, transitions),
1191+
commitRoot.bind(
1192+
null,
1193+
root,
1194+
recoverableErrors,
1195+
transitions,
1196+
didIncludeRenderPhaseUpdate,
1197+
),
11811198
);
11821199
markRootSuspended(root, lanes);
11831200
return;
11841201
}
11851202
}
11861203

11871204
// Otherwise, commit immediately.
1188-
commitRoot(root, recoverableErrors, transitions);
1205+
commitRoot(root, recoverableErrors, transitions, didIncludeRenderPhaseUpdate);
11891206
}
11901207

11911208
function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean {
@@ -1241,17 +1258,51 @@ function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean {
12411258
return true;
12421259
}
12431260

1261+
// The extra indirections around markRootUpdated and markRootSuspended is
1262+
// needed to avoid a circular dependency between this module and
1263+
// ReactFiberLane. There's probably a better way to split up these modules and
1264+
// avoid this problem. Perhaps all the root-marking functions should move into
1265+
// the work loop.
1266+
1267+
function markRootUpdated(root: FiberRoot, updatedLanes: Lanes) {
1268+
_markRootUpdated(root, updatedLanes);
1269+
1270+
// Check for recursive updates
1271+
if (executionContext & RenderContext) {
1272+
workInProgressRootDidIncludeRecursiveRenderUpdate = true;
1273+
} else if (executionContext & CommitContext) {
1274+
didIncludeCommitPhaseUpdate = true;
1275+
}
1276+
1277+
throwIfInfiniteUpdateLoopDetected();
1278+
}
1279+
1280+
function markRootPinged(root: FiberRoot, pingedLanes: Lanes) {
1281+
_markRootPinged(root, pingedLanes);
1282+
1283+
// Check for recursive pings. Pings are conceptually different from updates in
1284+
// other contexts but we call it an "update" in this context because
1285+
// repeatedly pinging a suspended render can cause a recursive render loop.
1286+
// The relevant property is that it can result in a new render attempt
1287+
// being scheduled.
1288+
if (executionContext & RenderContext) {
1289+
workInProgressRootDidIncludeRecursiveRenderUpdate = true;
1290+
} else if (executionContext & CommitContext) {
1291+
didIncludeCommitPhaseUpdate = true;
1292+
}
1293+
1294+
throwIfInfiniteUpdateLoopDetected();
1295+
}
1296+
12441297
function markRootSuspended(root: FiberRoot, suspendedLanes: Lanes) {
12451298
// When suspending, we should always exclude lanes that were pinged or (more
12461299
// rarely, since we try to avoid it) updated during the render phase.
1247-
// TODO: Lol maybe there's a better way to factor this besides this
1248-
// obnoxiously named function :)
12491300
suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
12501301
suspendedLanes = removeLanes(
12511302
suspendedLanes,
12521303
workInProgressRootInterleavedUpdatedLanes,
12531304
);
1254-
markRootSuspended_dontCallThisOneDirectly(root, suspendedLanes);
1305+
_markRootSuspended(root, suspendedLanes);
12551306
}
12561307

12571308
// This is the entry point for synchronous tasks that don't go
@@ -1324,6 +1375,7 @@ export function performSyncWorkOnRoot(root: FiberRoot, lanes: Lanes): null {
13241375
root,
13251376
workInProgressRootRecoverableErrors,
13261377
workInProgressTransitions,
1378+
workInProgressRootDidIncludeRecursiveRenderUpdate,
13271379
);
13281380

13291381
// Before exiting, make sure there's a callback scheduled for the next
@@ -1538,6 +1590,7 @@ function prepareFreshStack(root: FiberRoot, lanes: Lanes): Fiber {
15381590
workInProgressRootPingedLanes = NoLanes;
15391591
workInProgressRootConcurrentErrors = null;
15401592
workInProgressRootRecoverableErrors = null;
1593+
workInProgressRootDidIncludeRecursiveRenderUpdate = false;
15411594

15421595
finishQueueingConcurrentUpdates();
15431596

@@ -2582,6 +2635,7 @@ function commitRoot(
25822635
root: FiberRoot,
25832636
recoverableErrors: null | Array<CapturedValue<mixed>>,
25842637
transitions: Array<Transition> | null,
2638+
didIncludeRenderPhaseUpdate: boolean,
25852639
) {
25862640
// TODO: This no longer makes any sense. We already wrap the mutation and
25872641
// layout phases. Should be able to remove.
@@ -2595,6 +2649,7 @@ function commitRoot(
25952649
root,
25962650
recoverableErrors,
25972651
transitions,
2652+
didIncludeRenderPhaseUpdate,
25982653
previousUpdateLanePriority,
25992654
);
26002655
} finally {
@@ -2609,6 +2664,7 @@ function commitRootImpl(
26092664
root: FiberRoot,
26102665
recoverableErrors: null | Array<CapturedValue<mixed>>,
26112666
transitions: Array<Transition> | null,
2667+
didIncludeRenderPhaseUpdate: boolean,
26122668
renderPriorityLevel: EventPriority,
26132669
) {
26142670
do {
@@ -2688,6 +2744,9 @@ function commitRootImpl(
26882744

26892745
markRootFinished(root, remainingLanes);
26902746

2747+
// Reset this before firing side effects so we can detect recursive updates.
2748+
didIncludeCommitPhaseUpdate = false;
2749+
26912750
if (root === workInProgressRoot) {
26922751
// We can reset these now that they are finished.
26932752
workInProgressRoot = null;
@@ -2940,6 +2999,16 @@ function commitRootImpl(
29402999
// hydration lanes in this check, because render triggered by selective
29413000
// hydration is conceptually not an update.
29423001
if (
3002+
// Check if there was a recursive update spawned by this render, in either
3003+
// the render phase or the commit phase. We track these explicitly because
3004+
// we can't infer from the remaining lanes alone.
3005+
didIncludeCommitPhaseUpdate ||
3006+
didIncludeRenderPhaseUpdate ||
3007+
// As an additional precaution, we also check if there's any remaining sync
3008+
// work. Theoretically this should be unreachable but if there's a mistake
3009+
// in React it helps to be overly defensive given how hard it is to debug
3010+
// those scenarios otherwise. This won't catch recursive async updates,
3011+
// though, which is why we check the flags above first.
29433012
// Was the finished render the result of an update (not hydration)?
29443013
includesSomeLane(lanes, UpdateLanes) &&
29453014
// Did it schedule a sync update?
@@ -3486,6 +3555,17 @@ export function throwIfInfiniteUpdateLoopDetected() {
34863555
rootWithNestedUpdates = null;
34873556
rootWithPassiveNestedUpdates = null;
34883557

3558+
if (executionContext & RenderContext && workInProgressRoot !== null) {
3559+
// We're in the render phase. Disable the concurrent error recovery
3560+
// mechanism to ensure that the error we're about to throw gets handled.
3561+
// We need it to trigger the nearest error boundary so that the infinite
3562+
// update loop is broken.
3563+
workInProgressRoot.errorRecoveryDisabledLanes = mergeLanes(
3564+
workInProgressRoot.errorRecoveryDisabledLanes,
3565+
workInProgressRootRenderLanes,
3566+
);
3567+
}
3568+
34893569
throw new Error(
34903570
'Maximum update depth exceeded. This can happen when a component ' +
34913571
'repeatedly calls setState inside componentWillUpdate or ' +

scripts/jest/matchers/toWarnDev.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,16 @@ const createMatcherFor = (consoleMethod, matcherName) =>
6969
(message.includes('\n in ') || message.includes('\n at '));
7070

7171
const consoleSpy = (format, ...args) => {
72-
// Ignore uncaught errors reported by jsdom
73-
// and React addendums because they're too noisy.
7472
if (
75-
!logAllErrors &&
76-
consoleMethod === 'error' &&
77-
shouldIgnoreConsoleError(format, args)
73+
// Ignore uncaught errors reported by jsdom
74+
// and React addendums because they're too noisy.
75+
(!logAllErrors &&
76+
consoleMethod === 'error' &&
77+
shouldIgnoreConsoleError(format, args)) ||
78+
// Ignore error objects passed to console.error, which we sometimes
79+
// use as a fallback behavior, like when reportError
80+
// isn't available.
81+
typeof format !== 'string'
7882
) {
7983
return;
8084
}

0 commit comments

Comments
 (0)