async函数调用Firebase addDoc成功后then()内清空数组不生效如何解决
问题原因及解决方案
问题根因
你的问题出在代码执行顺序逻辑混乱:
- 函数开头先清空了
this.errors,当this.name和this.phone都有值时,会进入异步提交逻辑 await关键字会阻塞后续代码执行,直到addDoc的异步请求完成- 请求成功的
then回调里你把this.name、this.phone都设为空,同时清空了this.errors - 异步执行完成后,函数会继续往下走,触发后面的两个非空判断:此时
this.name和this.phone已经被清空,所以会再次把"name"、"phone"推入this.errors数组,表现出来就是清空操作不生效。
修复方案
你可以把表单校验逻辑移到异步提交之前,校验不通过直接终止执行,避免提交后再触发校验逻辑,同时建议统一用try/catch处理异步逻辑,避免await和then/catch混用导致逻辑混乱,修改后的参考代码如下:
saveContact: async function() { // 前置校验逻辑,不通过直接返回 this.errors = []; if (!this.name) this.errors.push("name"); if (!this.phone) this.errors.push("phone"); if (this.errors.length > 0) return; // 校验通过才执行提交 this.loading = true; try { await addDoc(collection(db, "users"), { id: this.id, name: this.name, phone: this.phone }); // 提交成功后清空表单 this.name = "" this.phone = "" this.errors = []; } catch (error) { this.error = error } finally { // 无论提交成功失败都重置loading状态 this.loading = false; } }
内容的提问来源于stack exchange,提问作者Kamal
相关产品推荐
相关产品推荐

