在我的通用 React 应用程序中,我在 componentWillMount
和 clearInterval< 中有一个包含
在 setInterval
的 React 组件componentWillUnmount
中。
幸运的是,componentWillUnmount
没有在服务器上调用。
componentWillMount(){
this.checker = setInterval(this.checkForSubscription, 2000);
}
componentWillUnmount(){
clearInterval(this.checker);
}
我的 express 服务器出现崩溃和内存泄漏问题。我创建了堆转储并在 chrome 内存工具上分析了这些。
不幸的是,没有成功找到内存泄漏。因此,当我通过检查窗口对象的 typeof
从服务器端逻辑中删除 setInterval
时。从那以后我没有制造任何崩溃。所以,我想知道上面的代码是内存泄漏的原因,为什么?
最佳答案
您可以安全地将您的方法迁移到未在服务器上调用的 componenDidMount
componentDidlMount(){
this.checker = setInterval(this.checkForSubscription, 2000);
}
componentWillUnmount(){
clearInterval(this.checker);
}
您还可以使用更多的包,例如 can-use-dom
import canUseDOM from 'can-use-dom';
componentWillMount(){
canUseDOM && this.checker = setInterval(this.checkForSubscription, 2000);
}
componentWillUnmount(){
clearInterval(this.checker);
}
如果你使用的是 webpack,你可以在配置中定义一个环境变量
new webpack.DefinePlugin({
'process.env': {
BROWSER: JSON.stringify(true),
},
}),
并使用条件 process.env.BROWSER && "your code"
关于javascript - React 服务器端 + Nodejs setInterval 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969931/