【发布时间】:2019-03-10 06:32:23
【问题描述】:
我的应用程序中的几个组件出现以下错误。
警告:无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。
导致此问题的组件之一在 componentWillUnmount 方法中有一个调整大小删除事件侦听器。我该如何解决这个问题。从我在在线示例中看到的情况来看,在这种方法中取消订阅事件是很常见的。
我不允许粘贴特定代码,所以我正在编写伪代码
clickHandler() {
this.setState({ opened: !(this.state.opened) });
}
componentDidMount() {
this.setState({ width: window.innerWidth } );
window.addEventListener('resize', this.updateWidth);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWidth);
}
private updateWidth() {
if (this.state.opened &&
window.innerWidth >= someMethodReturnsViewportConstant()) {
this.onClickHandler();
const htmlElement: HTMLInputElement =
document.querySelector('#html-element-id');
if (htmlElement && htmlElement) {
htmlElement = false;
}
}
}
我做了什么:
我已阅读 Stack 上有关此问题的所有帖子,但没有人解释我的代码导致此问题的原因。
【问题讨论】:
-
如果您在 setTimeout 中执行 setState,请确保使用 clearTimeout() 函数在 componentWillUnMount 中清除所有这些
-
我没有在任何地方使用 setTimout。我在 componentWillMount 方法中订阅事件监听器并将状态设置为 this.setState({ width: window.innerWidth } );
-
您在组件中使用的是 componentWillRecieveProps 还是 componentDidUpdate?
-
我没有使用它们。
-
抱歉 给定的代码帮不了你太多。需要查看问题的完整组件代码
标签: javascript reactjs