发布于 

消除 Vue 中 Unhandled error during execution of xxx 的警告

以 Vue3 为例,通常我们会在 onMounted 钩子中处理异步请求

1
2
3
4
onMounted(() => {
await request()
fn() // fn 只在 request 请求成功后被调用
})

如果 request 请求出错而未处理,Vue 会抛出警告

虽然影响并不大,可警告看着还是不太舒服,索性还是想办法解决下

可通过下面几种方式消除警告

try…catch

缺点:太丑了

1
2
3
4
5
6
7
8
onMounted(() => {
try {
await request()
} catch(error) {
return
}
fn() // fn 只在 request 请求成功后被调用
})

await…catch

缺点:需要额外对错误类型进行判断

1
2
3
4
5
onMounted(() => {
const result = await request()!.catch(error => new Error())
if(result instanceof Error) return
fn()
})

.then

推荐使用,这时候 thenawait 好用

1
2
3
onMounted(() => {
request()?.then(fn, () => undefined)
})

(●'◡'●)ノ♥