Firebase文档更新报错Unsupported field value: undefined 如何解决?
解决Firebase DocumentReference.update()的Undefined字段值错误
这个错误我之前也碰到过,核心原因是回调函数里的this上下文丢失,导致你在update()里访问this.editedItem时拿到的是undefined,进而传给Firebase的字段值变成了undefined,触发了它的校验规则错误。
在你的代码里,querySnapshot.forEach()的普通函数回调会创建自己的this上下文,不再指向Vue组件实例,所以里面的this.editedItem其实是undefined,自然拿不到name和description属性。
解决方案1:使用箭头函数(最简洁的方式)
箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的Vue组件实例)。只需要把forEach的回调改成箭头函数即可:
save() { if (this.editedIndex > -1) { db.collection('categories').where('id', '==', this.editedItem.id).get().then( (querySnapshot) => { // 改用箭头函数,保留外层的this指向 querySnapshot.forEach((doc) => { doc.ref.update({ name: this.editedItem.name, description: this.editedItem.description }).then(() => { this.$router.push('/categories') }) }) }) } }
解决方案2:提前保存Vue实例的引用
如果不习惯用箭头函数,可以在进入异步回调前,先把Vue实例的this存到一个变量里(比如vm),然后在回调里用这个变量访问组件属性:
save() { if (this.editedIndex > -1) { // 保存Vue实例的引用 const vm = this db.collection('categories').where('id', '==', vm.editedItem.id).get().then( (querySnapshot) => { querySnapshot.forEach(function(doc) { doc.ref.update({ name: vm.editedItem.name, description: vm.editedItem.description }).then(() => { vm.$router.push('/categories') }) }) }) } }
额外验证步骤
如果修改后还是报错,建议在save方法开头先打印this.editedItem,确认name和description确实有值,排除是表单绑定或其他逻辑导致的属性丢失:
save() { console.log('当前editedItem:', this.editedItem) // 确认属性是否存在 if (this.editedIndex > -1) { // ... 后续代码 } }
内容的提问来源于stack exchange,提问作者SSFS
相关产品推荐
相关产品推荐

