From fe0f47f6dc25212da83f7daf478110c0f679fa34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Berg=C3=A9?= Date: Wed, 12 Dec 2018 00:13:18 +0100 Subject: [PATCH] fix: ensure that component is mounted before calling `setState` (#184) Closes #180 --- packages/component/src/createLoadable.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/component/src/createLoadable.js b/packages/component/src/createLoadable.js index 60b41f62..1bf582a4 100644 --- a/packages/component/src/createLoadable.js +++ b/packages/component/src/createLoadable.js @@ -59,6 +59,8 @@ function createLoadable({ resolve = identity, render, onLoad }) { } componentDidMount() { + this.mounted = true + if (this.state.loading) { this.loadAsync() } else if (!this.state.error) { @@ -66,6 +68,16 @@ function createLoadable({ resolve = identity, render, onLoad }) { } } + componentWillUnmount() { + this.mounted = false + } + + safeSetState(nextState, callback) { + if (this.mounted) { + this.setState(nextState, callback) + } + } + triggerOnLoad() { if (onLoad) { setTimeout(() => { @@ -93,7 +105,7 @@ function createLoadable({ resolve = identity, render, onLoad }) { ctor .requireAsync(this.props) .then(loadedModule => { - this.setState( + this.safeSetState( { result: resolve(loadedModule, { Loadable }), loading: false, @@ -102,7 +114,7 @@ function createLoadable({ resolve = identity, render, onLoad }) { ) }) .catch(error => { - this.setState({ error, loading: false }) + this.safeSetState({ error, loading: false }) }) return this.promise