Vue中调用导出Axios函数时.then()未定义的问题求助
问题:调用Axios封装方法时提示
.then()未定义 问题代码
Vue组件中的调用代码
stopAll(){ startmeetingApi.stop().then((res) => { this.transcript = res.data.transcript; }); console.log(this.transcript); // 异步未完成时会输出初始值 // this.$router.go(); },
封装的startmeetingApi.stop方法
stop(){ recorder.stop().getMp3().then(([buffer, blob]) => { const file = new File(buffer, 'test.mp3', { type: blob.type, lastModified: Date.now() }); const formData = new FormData(); formData.append("data", file); return Axios.post("http://voice-app.test/api/v1/file", formData, { headers: { 'Authorization': `Bearer ${localStorage.getItem("Bearer")}`, } }).catch((e) => { console.error(e); }) }).catch((e) => { console.error(e); }) }
报错信息
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
问题原因
stop方法内部存在Promise链式调用,但没有返回整个Promise链,函数默认返回undefined。在Vue中调用startmeetingApi.stop().then()时,相当于在undefined上调用.then(),因此触发报错。
另外,Vue代码里的console.log(this.transcript)会先于.then()执行,因为异步操作尚未完成,此时this.transcript仍是初始值。
解决方案
1. 修改stop方法,返回Promise链
给recorder.stop().getMp3()这条Promise链添加return,让stop函数返回一个Promise,外部就能正常调用.then()。同时建议将错误捕获移到外部统一处理,避免内部吃掉错误导致外部无法感知:
stop(){ // 返回整个Promise链 return recorder.stop().getMp3().then(([buffer, blob]) => { const file = new File(buffer, 'test.mp3', { type: blob.type, lastModified: Date.now() }); const formData = new FormData(); formData.append("data", file); return Axios.post("http://voice-app.test/api/v1/file", formData, { headers: { 'Authorization': `Bearer ${localStorage.getItem("Bearer")}`, } }); }); }
2. 调整Vue中的调用逻辑
将console.log移到.then()内部,确保能获取到异步返回的结果;同时添加catch统一处理错误:
stopAll(){ startmeetingApi.stop() .then((res) => { this.transcript = res.data.transcript; console.log(this.transcript); // 此时能拿到正确结果 // this.$router.go(); }) .catch((e) => { console.error(e); // 统一处理错误 }); },
内容的提问来源于stack exchange,提问作者jop frenken
相关产品推荐
相关产品推荐

