From d4dd3408bd98dfc67172412f5de6d5cec9a6bc2e Mon Sep 17 00:00:00 2001 From: Andrew Clark Date: Fri, 2 Dec 2016 18:13:51 -0800 Subject: [PATCH] Remove tryComponentDidMount/Update in favor of commit phase try block We still need tryComponentWillUnmount because deletion should be non- interruptible. Refactoring the commit phase to better handle errors also allows us to switch between fast and slow versions of the work loop. The slower version runs whenever there are captured errors; it must check each unit of work to see if it has failed. The faster version runs in the normal case where there are no errors. Whenever an error is thrown, we switch from the fast work loop to the slow work loop. --- .../shared/fiber/ReactFiberCommitWork.js | 94 +++--- .../shared/fiber/ReactFiberScheduler.js | 315 ++++++++++-------- .../shared/fiber/ReactFiberUpdateQueue.js | 16 +- .../fiber/__tests__/ReactIncremental-test.js | 3 +- 4 files changed, 234 insertions(+), 194 deletions(-) diff --git a/src/renderers/shared/fiber/ReactFiberCommitWork.js b/src/renderers/shared/fiber/ReactFiberCommitWork.js index 36cf684b28..8028fd9323 100644 --- a/src/renderers/shared/fiber/ReactFiberCommitWork.js +++ b/src/renderers/shared/fiber/ReactFiberCommitWork.js @@ -35,7 +35,7 @@ var { module.exports = function( config : HostConfig, - captureError : (failedFiber : Fiber, error: Error, isUnmounting : boolean) => Fiber | null + captureError : (failedFiber : Fiber, error: Error) => Fiber | null ) { const commitUpdate = config.commitUpdate; @@ -204,15 +204,17 @@ module.exports = function( } } - function commitNestedUnmounts(root : Fiber): void { + function commitNestedUnmounts(root : Fiber): boolean { // While we're inside a removed host node we don't want to call // removeChild on the inner nodes because they're removed by the top // call anyway. We also want to call componentWillUnmount on all // composites before this host node is removed from the tree. Therefore // we do an inner loop while we're still inside the host node. + let noErrors = true; let node : Fiber = root; while (true) { - commitUnmount(node); + const noError = commitUnmount(node); + noErrors = noErrors && noError; if (node.child) { // TODO: Coroutines need to visit the stateNode. node.child.return = node; @@ -220,26 +222,32 @@ module.exports = function( continue; } if (node === root) { - return; + return noErrors; } while (!node.sibling) { if (!node.return || node.return === root) { - return; + return noErrors; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } + // This is unreachable but without it Flow complains about implicitly- + // returned undefined. + return noErrors; // eslint-disable-line no-unreachable } - function unmountHostComponents(parent, current): void { + // Returns true if it completed without any errors + function unmountHostComponents(parent, current): boolean { // We only have the top Fiber that was inserted but we need recurse down its // children to find all the terminal nodes. + let noErrors = true; let node : Fiber = current; while (true) { if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node); + const noError = commitNestedUnmounts(node); + noErrors = noErrors && noError; // After all the children have unmounted, it is now safe to remove the // node from the tree. removeChild(parent, node.stateNode); @@ -252,7 +260,8 @@ module.exports = function( continue; } } else { - commitUnmount(node); + const noError = commitUnmount(node); + noErrors = noErrors && noError; if (node.child) { // TODO: Coroutines need to visit the stateNode. node.child.return = node; @@ -261,11 +270,11 @@ module.exports = function( } } if (node === current) { - return; + return noErrors; } while (!node.sibling) { if (!node.return || node.return === current) { - return; + return noErrors; } node = node.return; if (node.tag === HostPortal) { @@ -277,13 +286,16 @@ module.exports = function( node.sibling.return = node.return; node = node.sibling; } + // This is unreachable but without it Flow complains about implicitly- + // returned undefined. + return noErrors; // eslint-disable-line no-unreachable } - function commitDeletion(current : Fiber) : void { + function commitDeletion(current : Fiber) : boolean { // Recursively delete all host nodes from the parent. const parent = getHostParent(current); // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(parent, current); + const noErrors = unmountHostComponents(parent, current); // Cut off the return pointers to disconnect it from the tree. Ideally, we // should clear the child pointer of the parent alternate to let this @@ -296,9 +308,12 @@ module.exports = function( current.alternate.child = null; current.alternate.return = null; } + return noErrors; } - function commitUnmount(current : Fiber) : void { + // Returns true if it completed without any errors + function commitUnmount(current : Fiber) : boolean { + let noErrors = true; switch (current.tag) { case ClassComponent: { detachRef(current); @@ -306,25 +321,28 @@ module.exports = function( if (typeof instance.componentWillUnmount === 'function') { const error = tryCallComponentWillUnmount(instance); if (error) { - captureError(current, error, true); + captureError(current, error); + noErrors = false; } } - return; + break; } case HostComponent: { detachRef(current); - return; + break; } case CoroutineComponent: { - commitNestedUnmounts(current.stateNode); - return; + const noError = commitNestedUnmounts(current.stateNode); + noErrors = noErrors && noError; + break; } case HostPortal: { // TODO: this is recursive. commitDeletion(current); - return; + break; } } + return noErrors; } function commitWork(current : ?Fiber, finishedWork : Fiber) : void { @@ -369,17 +387,16 @@ module.exports = function( switch (finishedWork.tag) { case ClassComponent: { const instance = finishedWork.stateNode; - let firstError = null; if (finishedWork.effectTag & Update) { if (!current) { if (typeof instance.componentDidMount === 'function') { - firstError = tryCallComponentDidMount(instance); + instance.componentDidMount(); } } else { if (typeof instance.componentDidUpdate === 'function') { const prevProps = current.memoizedProps; const prevState = current.memoizedState; - firstError = tryCallComponentDidUpdate(instance, prevProps, prevState); + instance.componentDidUpdate(prevProps, prevState); } } attachRef(current, finishedWork, instance); @@ -390,26 +407,19 @@ module.exports = function( } if (finishedWork.effectTag & Callback) { if (finishedWork.callbackList) { - const callbackError = callCallbacks(finishedWork.callbackList, instance); - firstError = firstError || callbackError; + const callbackList = finishedWork.callbackList; finishedWork.callbackList = null; + callCallbacks(callbackList, instance); } } - if (firstError) { - captureError(finishedWork, firstError, false); - } return; } case HostRoot: { const rootFiber = finishedWork.stateNode; - let firstError = null; if (rootFiber.callbackList) { - const { callbackList } = rootFiber; + const callbackList = rootFiber.callbackList; rootFiber.callbackList = null; - firstError = callCallbacks(callbackList, rootFiber.current.child.stateNode); - } - if (firstError) { - captureError(rootFiber, firstError, false); + callCallbacks(callbackList, rootFiber.current.child.stateNode); } return; } @@ -431,24 +441,6 @@ module.exports = function( } } - function tryCallComponentDidMount(instance) { - try { - instance.componentDidMount(); - return null; - } catch (error) { - return error; - } - } - - function tryCallComponentDidUpdate(instance, prevProps, prevState) { - try { - instance.componentDidUpdate(prevProps, prevState); - return null; - } catch (error) { - return error; - } - } - function tryCallComponentWillUnmount(instance) { try { instance.componentWillUnmount(); diff --git a/src/renderers/shared/fiber/ReactFiberScheduler.js b/src/renderers/shared/fiber/ReactFiberScheduler.js index b2594e3758..4121126941 100644 --- a/src/renderers/shared/fiber/ReactFiberScheduler.js +++ b/src/renderers/shared/fiber/ReactFiberScheduler.js @@ -93,13 +93,15 @@ module.exports = function(config : HostConfig) { let nextScheduledRoot : ?FiberRoot = null; let lastScheduledRoot : ?FiberRoot = null; - // Keep track of which host environment callbacks are scheduled + // Keep track of which host environment callbacks are scheduled. let isAnimationCallbackScheduled : boolean = false; let isDeferredCallbackScheduled : boolean = false; let capturedErrors : Map | null = null; let firstUncaughtError : Error | null = null; + let isUnmounting : boolean = false; + function scheduleAnimationCallback(callback) { if (!isAnimationCallbackScheduled) { isAnimationCallbackScheduled = true; @@ -116,7 +118,7 @@ module.exports = function(config : HostConfig) { function findNextUnitOfWork() { if (pendingCommit) { - return null; + return pendingCommit; } // Clear out roots with no more work on them, or if they have uncaught errors @@ -163,7 +165,10 @@ module.exports = function(config : HostConfig) { return null; } - function commitAllWork(finishedWork : Fiber) { + // Returns true if the commit phase finishes without any errors. + function commitAllWork(finishedWork : Fiber): boolean { + let noErrors = true; + pendingCommit = null; const root : FiberRoot = (finishedWork.stateNode : any); resetWorkPriority(finishedWork); @@ -182,6 +187,7 @@ module.exports = function(config : HostConfig) { // ref unmounts. let effectfulFiber = finishedWork.firstEffect; pass1: while (true) { + let didHandleRoot = false; try { while (effectfulFiber) { if (effectfulFiber.effectTag & ContentReset) { @@ -222,29 +228,36 @@ module.exports = function(config : HostConfig) { break; } case Deletion: { - commitDeletion(effectfulFiber); + isUnmounting = true; + const noError = commitDeletion(effectfulFiber); + noErrors = noErrors && noError; + isUnmounting = false; break; } } effectfulFiber = effectfulFiber.nextEffect; } - } catch (error) { - if (effectfulFiber) { - captureError(effectfulFiber, error, false); - effectfulFiber = effectfulFiber.nextEffect; - continue pass1; + + // Finally if the root itself had an effect, we perform that since it is + // not part of the effect list. + if (!didHandleRoot && finishedWork.effectTag !== NoEffect) { + didHandleRoot = true; + const current = finishedWork.alternate; + commitWork(current, finishedWork); } + } catch (error) { + noErrors = false; + captureError(effectfulFiber || null, error); + if (effectfulFiber) { + effectfulFiber = effectfulFiber.nextEffect; + } + // Clean-up + isUnmounting = false; + continue pass1; } break; } - // Finally if the root itself had an effect, we perform that since it is - // not part of the effect list. - if (finishedWork.effectTag !== NoEffect) { - const current = finishedWork.alternate; - commitWork(current, finishedWork); - } - resetAfterCommit(); // Next, we'll perform all life-cycles and ref callbacks. Life-cycles @@ -254,6 +267,7 @@ module.exports = function(config : HostConfig) { const previousPriorityContext = priorityContext; priorityContext = TaskPriority; pass2: while (true) { + let didHandleRoot = false; try { while (effectfulFiber) { const current = effectfulFiber.alternate; @@ -276,28 +290,31 @@ module.exports = function(config : HostConfig) { // tags to reason about the current life-cycle. effectfulFiber = next; } + + // Finally if the root itself had an effect, we perform that since it is + // not part of the effect list. + if (!didHandleRoot && finishedWork.effectTag !== NoEffect) { + didHandleRoot = true; + const current = finishedWork.alternate; + commitLifeCycles(current, finishedWork); + if (finishedWork.effectTag & Err) { + commitErrorHandling(finishedWork); + } + } } catch (error) { + noErrors = false; + captureError(effectfulFiber || null, error); if (effectfulFiber) { - captureError(effectfulFiber, error, false); const next = effectfulFiber.nextEffect; effectfulFiber.nextEffect = null; effectfulFiber = next; - continue pass2; } + continue pass2; } priorityContext = previousPriorityContext; break; } - // Lifecycles on the root itself - if (finishedWork.effectTag !== NoEffect) { - const current = finishedWork.alternate; - commitLifeCycles(current, finishedWork); - if (finishedWork.effectTag & Err) { - commitErrorHandling(finishedWork); - } - } - if (capturedErrors) { if (capturedErrors.size) { capturedErrors.forEach((error, boundary) => { @@ -308,7 +325,9 @@ module.exports = function(config : HostConfig) { } } - return null; + nextUnitOfWork = null; + + return noErrors; } function resetWorkPriority(workInProgress : Fiber) { @@ -492,58 +511,27 @@ module.exports = function(config : HostConfig) { } function workLoop(priorityLevel) { - // If there are errors, use a forked version of performUnitOfWork - // TODO: Need to make commitAllWork throw on error before doing this - if (true || (capturedErrors && capturedErrors.size)) { - while (true) { - if (!nextUnitOfWork && !pendingCommit) { - nextUnitOfWork = findNextUnitOfWork(); - } - if (pendingCommit && !(priorityLevel === TaskPriority && pendingCommit.pendingWorkPriority !== TaskPriority)) { - nextUnitOfWork = commitAllWork(pendingCommit); - } else if (nextUnitOfWork && nextPriorityLevel !== NoWork && nextPriorityLevel <= priorityLevel) { - if (capturedErrors && capturedErrors.has(nextUnitOfWork)) { - nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork); - } else { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - } - } else { - return; - } - } - } - - // Otherwise, handle the normal, faster case where there are no errors: - while (true) { - if (!nextUnitOfWork && !pendingCommit) { + outer: while (true) { + if (!nextUnitOfWork) { nextUnitOfWork = findNextUnitOfWork(); } - if (pendingCommit && !(priorityLevel === TaskPriority && pendingCommit.pendingWorkPriority !== TaskPriority)) { - nextUnitOfWork = commitAllWork(pendingCommit); - } else if (nextUnitOfWork && nextPriorityLevel !== NoWork && nextPriorityLevel <= priorityLevel) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - } else { - return; - } - } - } - function deferredWorkLoop(deadline) { - if (!nextUnitOfWork) { - nextUnitOfWork = findNextUnitOfWork(); - } - - // If there are errors, use a forked version of performUnitOfWork - // TODO: Need to make commitAllWork throw on error before doing this - if (true || (capturedErrors && capturedErrors.size)) { - while (true) { - if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { + // If there are errors, use a forked version of performUnitOfWork + // TODO: Need to make commitAllWork throw on error before doing this + if (capturedErrors && capturedErrors.size) { + while (true) { if (!nextUnitOfWork && !pendingCommit) { nextUnitOfWork = findNextUnitOfWork(); } - if (pendingCommit) { - nextUnitOfWork = commitAllWork(pendingCommit); - } else if (nextUnitOfWork) { + // If we're currently flushing Task work, but the pending commit does + // not have Task priority, don't commit it — we're at the end of a + // deferred work batch and the commit should happen in the next batch. + if ( + pendingCommit && + !(priorityLevel === TaskPriority && pendingCommit.pendingWorkPriority !== TaskPriority) + ) { + commitAllWork(pendingCommit); + } else if (nextUnitOfWork && nextPriorityLevel !== NoWork && nextPriorityLevel <= priorityLevel) { if (capturedErrors && capturedErrors.has(nextUnitOfWork)) { nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork); } else { @@ -552,27 +540,90 @@ module.exports = function(config : HostConfig) { } else { return; } + } + } + + // Otherwise, handle the normal, faster case where there are no errors: + while (true) { + if (!nextUnitOfWork && !pendingCommit) { + nextUnitOfWork = findNextUnitOfWork(); + } + // If we're currently flushing Task work, but the pending commit does + // not have Task priority, don't commit it — we're at the end of a + // deferred work batch and the commit should happen in the next batch. + if ( + pendingCommit && + !(priorityLevel === TaskPriority && pendingCommit.pendingWorkPriority !== TaskPriority) + ) { + const noError = commitAllWork(pendingCommit); + if (!noError) { + // There was an error during the commit phase. Restart the outer + // loop so we can switch to the slower version of the work loop that + // checks for failed work. + continue outer; + } + } else if (nextUnitOfWork && nextPriorityLevel !== NoWork && nextPriorityLevel <= priorityLevel) { + nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } else { return; } } } + } - // Otherwise, handle the normal, faster case where there are no errors: - while (true) { - if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { - if (!nextUnitOfWork && !pendingCommit) { - nextUnitOfWork = findNextUnitOfWork(); + function deferredWorkLoop(deadline) { + outer: while (true) { + if (!nextUnitOfWork) { + nextUnitOfWork = findNextUnitOfWork(); + } + + // If there are errors, use a forked version of performUnitOfWork + // TODO: Need to make commitAllWork throw on error before doing this + if (capturedErrors && capturedErrors.size) { + while (true) { + if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { + if (!nextUnitOfWork && !pendingCommit) { + nextUnitOfWork = findNextUnitOfWork(); + } + if (pendingCommit) { + commitAllWork(pendingCommit); + } else if (nextUnitOfWork) { + if (capturedErrors && capturedErrors.has(nextUnitOfWork)) { + nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork); + } else { + nextUnitOfWork = performUnitOfWork(nextUnitOfWork); + } + } else { + return; + } + } else { + return; + } } - if (pendingCommit) { - nextUnitOfWork = commitAllWork(pendingCommit); - } else if (nextUnitOfWork) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); + } + + // Otherwise, handle the normal, faster case where there are no errors: + while (true) { + if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { + if (!nextUnitOfWork && !pendingCommit) { + nextUnitOfWork = findNextUnitOfWork(); + } + if (pendingCommit) { + const noError = commitAllWork(pendingCommit); + if (!noError) { + // There was an error during the commit phase. Restart the outer + // loop so we can switch to the slower version of the work loop that + // checks for failed work. + continue outer; + } + } else if (nextUnitOfWork) { + nextUnitOfWork = performUnitOfWork(nextUnitOfWork); + } else { + return; + } } else { return; } - } else { - return; } } } @@ -585,51 +636,53 @@ module.exports = function(config : HostConfig) { // Perform work until either there's no more work at this priority level, or // (in the case of deferred work) we've run out of time. - while (priorityLevel !== NoWork) { - // Functions that contain a try-catch block are not optimizable by the - // JS engine. The hottest code paths have been extracted to separate - // functions, workLoop and deferredWorkLoop, which run on every unit of - // work. The loop we're in now runs infrequently: to flush task work at - // the end of a frame, or to restart after an error. + while (true) { try { - if (priorityLevel >= HighPriority) { - if (!deadline) { - throw new Error('Cannot perform deferred work without a deadline.'); + // Functions that contain a try-catch block are not optimizable by the + // JS engine. The hottest code paths have been extracted to separate + // functions, workLoop and deferredWorkLoop, which run on every unit of + // work. The loop we're in now runs infrequently: to flush task work at + // the end of a frame, or to restart after an error. + while (priorityLevel !== NoWork) { + if (priorityLevel >= HighPriority) { + if (!deadline) { + throw new Error('Cannot perform deferred work without a deadline.'); + } + // The deferred work loop will run until there's no time left in + // the current frame + deferredWorkLoop(deadline); + } else { + // The non-deferred work loop will run until there's no more work + // at the given priority level + workLoop(priorityLevel); } - // The deferred work loop will run until there's no time left in - // the current frame - deferredWorkLoop(deadline); - } else { - // The non-deferred work loop will run until there's no more work - // at the given priority level - workLoop(priorityLevel); - } - // Stop performing work - priorityLevel = NoWork; + // Stop performing work + priorityLevel = NoWork; - // There might still be work left. Depending on the priority, we should - // either perform it now or schedule a callback to perform it later. - switch (nextPriorityLevel) { - case SynchronousPriority: - case TaskPriority: - // Perform work immediately by switching the priority level - // and continuing the loop. - priorityLevel = nextPriorityLevel; - break; - case AnimationPriority: - scheduleAnimationCallback(performAnimationWork); - // Even though the next unit of work has animation priority, there - // may still be deferred work left over as well. I think this is - // only important for unit tests. In a real app, a deferred callback - // would be scheduled during the next animation frame. - scheduleDeferredCallback(performDeferredWork); - break; - case HighPriority: - case LowPriority: - case OffscreenPriority: - scheduleDeferredCallback(performDeferredWork); - break; + // There might still be work left. Depending on the priority, we should + // either perform it now or schedule a callback to perform it later. + switch (nextPriorityLevel) { + case SynchronousPriority: + case TaskPriority: + // Perform work immediately by switching the priority level + // and continuing the loop. + priorityLevel = nextPriorityLevel; + break; + case AnimationPriority: + scheduleAnimationCallback(performAnimationWork); + // Even though the next unit of work has animation priority, there + // may still be deferred work left over as well. I think this is + // only important for unit tests. In a real app, a deferred callback + // would be scheduled during the next animation frame. + scheduleDeferredCallback(performDeferredWork); + break; + case HighPriority: + case LowPriority: + case OffscreenPriority: + scheduleDeferredCallback(performDeferredWork); + break; + } } } catch (error) { // We caught an error during either the begin or complete phases. @@ -637,7 +690,7 @@ module.exports = function(config : HostConfig) { // "Capture" the error by finding the nearest boundary. If there is no // error boundary, the nearest host container acts as one. - const maybeBoundary = captureError(failedWork, error, false); + const maybeBoundary = captureError(failedWork, error); if (maybeBoundary) { const boundary = maybeBoundary; @@ -663,8 +716,10 @@ module.exports = function(config : HostConfig) { } nextUnitOfWork = completeUnitOfWork(boundary); } - // The loop will continue performing work + // Continue performing work + continue; } + break; } // We're done performing work. Time to clean up. @@ -681,7 +736,7 @@ module.exports = function(config : HostConfig) { } } - function captureError(failedWork : Fiber | null, error : Error, isUnmounting : boolean) : Fiber | null { + function captureError(failedWork : Fiber | null, error : Error) : Fiber | null { // It is no longer valid because we exited the user code. ReactCurrentOwner.current = null; // It is no longer valid because this unit of work failed. @@ -762,7 +817,7 @@ module.exports = function(config : HostConfig) { // an update to itself instance.unstable_handleError(error); } catch (e) { - captureError(effectfulFiber, e, false); + captureError(effectfulFiber, e); } return; case HostRoot: diff --git a/src/renderers/shared/fiber/ReactFiberUpdateQueue.js b/src/renderers/shared/fiber/ReactFiberUpdateQueue.js index 784e8b8a6b..5fe2eafdbe 100644 --- a/src/renderers/shared/fiber/ReactFiberUpdateQueue.js +++ b/src/renderers/shared/fiber/ReactFiberUpdateQueue.js @@ -66,25 +66,19 @@ exports.addCallbackToQueue = function(queue : UpdateQueue, callback: Function) : return queue; }; -exports.callCallbacks = function(queue : UpdateQueue, context : any) : Error | null { +exports.callCallbacks = function(queue : UpdateQueue, context : any) { let node : ?UpdateQueueNode = queue; - let firstError = null; while (node) { const callback = node.callback; if (callback) { - try { - if (typeof context !== 'undefined') { - callback.call(context); - } else { - callback(); - } - } catch (error) { - firstError = firstError || error; + if (typeof context !== 'undefined') { + callback.call(context); + } else { + callback(); } } node = node.next; } - return firstError; }; function getStateFromNode(node, instance, state, props) { diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index b4560cdcc3..2d823c9958 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -1497,11 +1497,10 @@ describe('ReactIncremental', () => { ReactNoop.flush(); }).toThrow('callback error'); - // Should call all callbacks, even though the second one throws + // The third callback isn't called because the second one throws expect(ops).toEqual([ 'first callback', 'second callback', - 'third callback', ]); expect(instance.state.n).toEqual(3); });