在Vue.js中使用Teachable Machine调用predict时报undefined错误如何解决
问题根因
报错的核心原因是window.requestAnimationFrame调用loop方法时,loop的this指向丢失,没有绑定到当前Vue组件实例,导致方法内访问this.webcam、this.model都为undefined。
解决方案
只需要修改requestAnimationFrame的传参方式,用箭头函数包裹调用即可保留组件实例的this指向:
- 修改
init方法里的window.requestAnimationFrame(this.loop)为window.requestAnimationFrame(() => this.loop()) - 修改
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
相关产品推荐
相关产品推荐

