Only Allow forceUpdate on Mounted Components

This commit is contained in:
CommitSyncScript
2013-06-06 14:29:44 -07:00
committed by Paul O’Shannessy
parent bae6100ae8
commit 11a7cb5b73
2 changed files with 43 additions and 0 deletions
+11
View File
@@ -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,
@@ -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 <div />;
}
});
var instance = <Component />;
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.'
);
});
});