Skip to content

Commit

Permalink
Handles risky callbacks on setState. Fixes facebook#8238
Browse files Browse the repository at this point in the history
  • Loading branch information
ankeetmaini committed Nov 12, 2016
1 parent 9d20191 commit b5e7c9c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/renderers/shared/fiber/ReactFiberUpdateQueue.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ exports.callCallbacks = function(queue : UpdateQueue, context : any) {
if (callback && !node.callbackWasCalled) {
node.callbackWasCalled = true;
if (typeof context !== 'undefined') {
callback.call(context);
try {
callback.call(context);
} catch (error) {
// do something
}
} else {
callback();
}
Expand Down
48 changes: 48 additions & 0 deletions src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1465,4 +1465,52 @@ describe('ReactIncremental', () => {
]);
expect(instance.state.n).toEqual(4);
});

it('can handle if setState callback throws', () => {
var ops = [];
var instance;

class Foo extends React.Component {
state = { n: 0 };
render() {
instance = this;
return <div />;
}
}

ReactNoop.render(<Foo />);
ReactNoop.flush();
ops = [];

ReactNoop.syncUpdates(() => {
ReactNoop.batchedUpdates(() => {
instance.setState({ n: 1 }, () => {
throw new Error('Bail!');
});
instance.setState({ n: 2 }, () => ops.push('setState 2'));
ReactNoop.batchedUpdates(() => {
instance.setState({ n: 3 }, () => ops.push('setState 3'));
instance.setState({ n: 4 }, () => {
throw new Error('Bail Again!');
});
instance.setState({ n: 5 }, () => ops.push('setState 5'));
ops.push('end inner batchedUpdates');
});
ops.push('end outer batchedUpdates');
});
ops.push('end syncUpdates');
});

// ReactNoop.flush() not needed because updates are synchronous

expect(ops).toEqual([
'end inner batchedUpdates',
'end outer batchedUpdates',
'setState 2',
'setState 3',
'setState 5',
'end syncUpdates',
]);
expect(instance.state.n).toEqual(5);
});
});

0 comments on commit b5e7c9c

Please sign in to comment.