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

为什么Vue的beforeDestroyed钩子无法正常清除setInterval定时器?

问题排查与修复方案

核心错误点

  • 未存储定时器ID:setInterval执行后会返回一个唯一的数字ID,这是clearInterval唯一可识别的清除依据,你当前代码直接将自定义方法this.clock作为入参传入清除方法,完全无法匹配到对应的定时器,因此清除失败。
  • (可选校验)生命周期钩子拼写问题:Vue 2.x的销毁前钩子名为beforeDestroy,Vue 3.x对应的销毁前钩子名为beforeUnmount,你使用的beforeDestroyed并非标准钩子名,如果你的运行环境没有特殊兼容,即使能打印日志也建议修正为对应框架版本的标准钩子名。

修复后代码

// 第一步:data中新增变量存储定时器ID
data() {
  return {
    timer: null
  }
},
methods: {
  clock() {     
    const date = new Date()
    const hours = ((date.getHours() + 11) % 12 + 1);
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const hour = hours * 30;
    const minute = minutes * 6;
    const second = seconds * 6;
    // 你原本的时钟渲染逻辑写在这里即可
}},
mounted: function() {
  // 第二步:存储定时器返回的ID
  this.timer = setInterval(this.clock, 1000);
},
// 第三步:修正钩子名,用存储的ID清除定时器
beforeDestroy: function() {
  console.log("workBefore")
  if (this.timer) {
    clearInterval(this.timer);
    this.timer = null;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 16:54:03