From 11a7cb5b734a1c28cce399fc8a56dbe43c7ce371 Mon Sep 17 00:00:00 2001 From: CommitSyncScript Date: Tue, 4 Jun 2013 12:52:27 -0700 Subject: [PATCH] Only Allow `forceUpdate` on Mounted Components --- src/core/ReactCompositeComponent.js | 11 +++++++ .../__tests__/ReactCompositeComponent-test.js | 32 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/core/ReactCompositeComponent.js b/src/core/ReactCompositeComponent.js index aabbfb4e86..fdf3d8e7ae 100644 --- a/src/core/ReactCompositeComponent.js +++ b/src/core/ReactCompositeComponent.js @@ -708,6 +708,17 @@ var ReactCompositeComponentMixin = { * @protected */ forceUpdate: function() { + var compositeLifeCycleState = this._compositeLifeCycleState; + invariant( + this._lifeCycleState === ReactComponent.LifeCycle.MOUNTED, + 'forceUpdate(...): Can only force an update on mounted components.' + ); + invariant( + compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE && + compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING, + 'forceUpdate(...): Cannot force an update while unmounting component ' + + 'or during an existing state transition (such as within `render`).' + ); var transaction = ReactComponent.ReactReconcileTransaction.getPooled(); transaction.perform( this._performComponentUpdate, diff --git a/src/core/__tests__/ReactCompositeComponent-test.js b/src/core/__tests__/ReactCompositeComponent-test.js index 51575277b3..f2b666321c 100644 --- a/src/core/__tests__/ReactCompositeComponent-test.js +++ b/src/core/__tests__/ReactCompositeComponent-test.js @@ -270,4 +270,36 @@ describe('ReactCompositeComponent', function() { }).not.toThrow(); }); + it('should not allow `forceUpdate` on unmounted components', function() { + var container = document.createElement('div'); + document.documentElement.appendChild(container); + + var Component = React.createClass({ + render: function() { + return
; + } + }); + + var instance = ; + expect(function() { + instance.forceUpdate(); + }).toThrow( + 'Invariant Violation: forceUpdate(...): Can only force an update on ' + + 'mounted components.' + ); + + React.renderComponent(instance, container); + expect(function() { + instance.forceUpdate(); + }).not.toThrow(); + + React.unmountAndReleaseReactRootNode(container); + expect(function() { + instance.forceUpdate(); + }).toThrow( + 'Invariant Violation: forceUpdate(...): Can only force an update on ' + + 'mounted components.' + ); + }); + });