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

在Vue.js中使用Teachable Machine调用predict时报undefined错误如何解决

问题根因

报错的核心原因是window.requestAnimationFrame调用loop方法时,loop的this指向丢失,没有绑定到当前Vue组件实例,导致方法内访问this.webcam、this.model都为undefined。

解决方案

只需要修改requestAnimationFrame的传参方式,用箭头函数包裹调用即可保留组件实例的this指向:

  1. 修改init方法里的window.requestAnimationFrame(this.loop)为window.requestAnimationFrame(() => this.loop())
  2. 修改loop方法里的window.requestAnimationFrame(this.loop)为window.requestAnimationFrame(() => this.loop())

如果需要更稳妥的绑定,也可以直接在methods中把loop定义为箭头函数:

loop: async () => {
  this.webcam.update();
  await this.predict();
  window.requestAnimationFrame(() => this.loop());
}

额外优化建议

  • 不要直接用document.getElementById操作DOM,给对应DOM节点加ref属性,通过this.$refs访问更符合Vue的使用规范
  • 组件销毁时需要清理动画帧回调、关闭摄像头,避免内存泄漏,示例如下:
// data中新增属性
data() {
  return {
    // ...其他原有属性
    animationId: null
  }
},
methods: {
  async loop() {
    this.webcam.update();
    await this.predict();
    // 存储回调ID
    this.animationId = window.requestAnimationFrame(() => this.loop());
  }
},
beforeUnmount() {
  // 销毁时清理
  if (this.animationId) {
    window.cancelAnimationFrame(this.animationId);
  }
  if (this.webcam) {
    this.webcam.stop();
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:33:03