Remove Error event listener eagerly instead of using depth count (#10296)
A little simpler.
Sebastian Markbåge committed
Jul 27, 2017 at 09:45 UTC
e1cfd6c082dae2e1472a6a051f6919725d9cfc91
1 file changed
+8
-15
src/renderers/shared/utils/ReactErrorUtils.js
+8
-15
@@ -36,7 +36,7 @@ const ReactErrorUtils = {
36
/**
37
* Call a function while guarding against errors that happens within it.
38
* Returns an error if it throws, otherwise null.
39
- *
39
+ *
40
* In production, this is implemented using a try-catch. The reason we don't
41
* use a try-catch directly is so that we can swap out a different
42
* implementation in DEV mode.
@@ -160,7 +160,6 @@ if (__DEV__) {
160
typeof document.createEvent === 'function'
161
) {
162
const fakeNode = document.createElement('react');
163
- let depth = 0;
163
164
const invokeGuardedCallbackDev = function(
165
name,
@@ -186,6 +185,11 @@ if (__DEV__) {
185
// call the user-provided callback.
186
const funcArgs = Array.prototype.slice.call(arguments, 3);
187
function callCallback() {
188
+ // We immediately remove the callback from event listeners so that
189
+ // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
190
+ // nested call would trigger the fake event handlers of any call higher
191
+ // in the stack.
192
+ fakeNode.removeEventListener(evtType, callCallback, false);
193
func.apply(context, funcArgs);
194
didError = false;
195
}
@@ -210,12 +214,8 @@ if (__DEV__) {
214
didSetError = true;
215
}
216
213
- // Create a fake event type. We add `depth` to the event name so that
214
- // nested `invokeGuardedCallback` calls do not clash. Otherwise, a nested
215
- // call would trigger the fake event handlers of any call higher in
216
- // the stack.
217
- depth++;
218
- const evtType = `react-${name ? name : 'invokeguardedcallback'}-${depth}`;
217
+ // Create a fake event type.
218
+ const evtType = `react-${name ? name : 'invokeguardedcallback'}`;
219
220
// Attach our event handlers
221
window.addEventListener('error', onError);
@@ -249,14 +249,7 @@ if (__DEV__) {
249
}
250
251
// Remove our event listeners
252
- fakeNode.removeEventListener(evtType, callCallback, false);
252
window.removeEventListener('error', onError);
254
-
255
- // Decrement the depth. This isn't strictly necessary, because we could
256
- // just keep incrementing the number; the only requirement is that no two
257
- // calls to `invokeGuardedCallback` use the same event type at the same
258
- // time. But this does prevent `depth` from increasing boundlessly.
259
- depth--;
253
};
254
255
invokeGuardedCallback = invokeGuardedCallbackDev;