You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件中计时器到7时,componentWillUnmount无法停止setInterval

React类组件计时器计数到7时无法停止setInterval的问题分析与解决

问题原因

componentWillUnmount() 是组件即将卸载时才会触发的生命周期函数,你想在counter等于7时停止定时器,但此时组件并未卸载,这段判断逻辑根本不会执行,所以定时器停不下来。

修复代码

把停止定时器的逻辑移到timer函数中,每次更新计数后检查是否达到7,同时使用setState的函数式更新避免异步状态更新的问题:

export default class App extends React.Component{
  constructor(props){
    super(props);
    this.state={
      counter:0
    }
  }

  componentDidMount(){
    this.timerID = setInterval(
      () => this.timer(),
      1000
    );
  }

  componentWillUnmount(){
    // 组件卸载时清除定时器,避免内存泄漏
    clearInterval(this.timerID);
  }

  timer = () => {
    this.setState(prevState => {
      const newCounter = prevState.counter + 1;
      // 计数到7时立即停止定时器
      if(newCounter === 7){
        clearInterval(this.timerID);
      }
      return { counter: newCounter };
    })
  }
}

关键说明

  • 使用setState的函数式更新(传入prevState参数),因为setState是异步操作,直接读取this.state可能拿到旧值,导致计数不准确。
  • 保留componentWillUnmount中的清除逻辑,防止组件在计数到7前被卸载时,定时器持续运行造成内存泄漏。

内容的提问来源于stack exchange,提问作者Syed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:25:42