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

Vue中如何在setTimeout等函数内部正确调用this.function

问题原因

你遇到的报错是setTimeout回调的this指向错误导致的:普通函数作为setTimeout回调执行时,this默认指向全局对象(浏览器环境下为window,严格模式下为undefined),而非当前Vue组件实例,因此无法访问到挂载在实例上的checkMounted方法。

解决方案

共有三种常用的修正方式:

  • 方案1:使用箭头函数作为回调(最推荐)
    箭头函数不会绑定独立的this,会继承外层作用域的this指向,也就是当前Vue组件实例:
mounted() {
  setTimeout(() => { 
     this.checkMounted()
  }, 3000); 
}
  • 方案2:外层预先缓存this
    在setTimeout外部将组件实例赋值给临时变量,回调内直接通过变量访问实例方法:
mounted() {
  const vm = this
  setTimeout(function(){ 
     vm.checkMounted()
  }, 3000); 
}
  • 方案3:通过bind方法绑定this
    使用Function.prototype.bind手动将回调函数的this绑定为当前组件实例:
mounted() {
  setTimeout(function(){ 
     this.checkMounted()
  }.bind(this), 3000); 
}

附加优化建议

使用定时器时建议将定时器id保存,在组件销毁前清除定时器,避免内存泄漏:

mounted() {
  // 保存定时器id
  this.timer = setTimeout(() => { 
     this.checkMounted()
  }, 3000); 
},
// Vue3使用beforeUnmount,Vue2使用beforeDestroy
beforeUnmount() {
  clearTimeout(this.timer)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:27:03