javascript - 由于“状态更新”,React 已安装组件 setInterval 未清除间隔
问题描述
我为一个函数设置了一个间隔计时器,该函数将今天的日期设置为我初始化的状态componenteDidMount
。虽然我清除了componentWillUnmount
.
这是错误:
警告: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
我曾尝试_isMounted
在整个周期中将私有变量从 false 操作为 true,并在setTodaysDate()
设置状态之前强制进行条件检查,但即使这样也没有解决问题。
// _isMounted = false; <----- tried this method to no avail
state = {
selectedDate: ""
};
componentDidMount() {
this.setTodaysDate();
this.interval = setInterval(() => this.setTodaysDate(), 40 * 1000 * 360);
// this._isMounted = true; <----- tried
}
componentWillUnmount() {
clearInterval(this.interval);
// this._isMounted = false; <----- tried
}
setTodaysDate = () => {
// if (this._isMounted) { <----- tried
this.setState({
selectedDate: moment(moment(), "YYYY-MM-DDTHH:mm:ss")
.add(1, "days")
.format("YYYY-MM-DD")
});
// } <----- tried
}
我不知道如何“堵塞泄漏”。
编辑:事实证明,多亏了下面的 Gabriele,真正的原因是我使用的 lodash debounce 方法(我也在其中 setState)在卸载期间从未取消,导致“泄漏”:
debounceCloseAlert = _.debounce(() => {
this.setState({ alertVisible: false });
}, 5000);
解决方案
查看您的组件,我认为问题不在于您的setInterval
. 您处理它的方式是正确的方法,不应产生上述错误。
我认为问题在于_.debounce
在您的debounceCloseAlert
方法中使用。它还会创建一个超时,您不会在任何地方清除它。
from 返回的值_.debounce
包括一个.cancel()
清除间隔的方法。所以只要打电话给this.debounceCloseAlert.cancel();
你componentWillUnmount
,它就会清除它。
推荐阅读
- python - CalDAV 或如何将 iCloud (Google...) 日历与我的应用程序同步?
- css - 我的更新页面的 css 没有正确加载,但其他页面工作得很好
- php - php(Laravel)中集合/数组的排名(重复)
- pandas - 为什么日期格式在 + MonthEnd(1) 之后变得奇怪
- r - 求解二次方程的 R 函数
- html - 无法在 Spring Boot 中加载图像
- postgresql - 如何使用 sequelize 对 postgres 中的数据进行分组并获取分组数据的实际值,而不是一些聚合函数?
- python - 我的递归方法不起作用 - 二分法
- android - 在从 ArrayAdapter 修改时访问 LinkedHashMap
- python - 有什么方法可以一步完成分组和计算统计度量吗?