Skip to content

Fix an internal crash when a reducer throws during render of another component #14675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/react-reconciler/src/ReactFiberHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -1054,14 +1054,16 @@ function dispatchAction<S, A>(
// same as the current state, we may be able to bail out entirely.
const eagerReducer = queue.eagerReducer;
if (eagerReducer !== null) {
// Note: this may be null and is *not* necessarily the `fiber`.
// In particular, they would be different if one component dispatches
// on another component in the render phase.
let savedCurrentlyRenderingFiber = currentlyRenderingFiber;
try {
const currentState: S = (queue.eagerState: any);
// Temporarily clear to forbid calling Hooks in a reducer.
let maybeFiber = currentlyRenderingFiber; // Note: likely null now unlike `fiber`
currentlyRenderingFiber = null;
stashContextDependencies();
const eagerState = eagerReducer(currentState, action);
currentlyRenderingFiber = maybeFiber;
unstashContextDependencies();
// Stash the eagerly computed state, and the reducer used to compute
// it, on the update object. If the reducer hasn't changed by the
Expand All @@ -1078,6 +1080,8 @@ function dispatchAction<S, A>(
}
} catch (error) {
// Suppress the error. It will throw again in the render phase.
} finally {
currentlyRenderingFiber = savedCurrentlyRenderingFiber;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -906,4 +906,32 @@ describe('ReactHooks', () => {
' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^',
]);
});

// Regression test for #14674
it('does not swallow original error when updating another component in render phase', () => {
let {useState} = React;

let _setState;
function A() {
const [, setState] = useState(0);
_setState = setState;
return null;
}

function B() {
_setState(() => {
throw new Error('Hello');
});
return null;
}

expect(() =>
ReactTestRenderer.create(
<React.Fragment>
<A />
<B />
</React.Fragment>,
),
).toThrow('Hello');
});
});