函数 DocumentReference.set() 使用无效数据调用。不支持的字段值:函数(在字段调度中找到)"



我正在尝试用vue、vuex构建一个web应用程序,并尝试将其与firebase数据库集成。但当我试图将数据发布到数据库时,会弹出这个错误:

[Vue warn]: Error in v-on handler (Promise/async): "FirebaseError: [code=invalid-argument]:
Function DocumentReference.set() called with invalid data. Unsupported field value:
a function (found in field dispatch)" found in 
---> <Subreddit> at src/views/Subreddit.vue
<App> at src/App.vue
<Root>

模块"Subreddit.vue"中的脚本代码是:

<script>
import { mapState, mapActions } from 'vuex';
export default {
data: () => ({
post: {
title: '',
description: '',
URL: '',
},
}),
computed: mapState('subreddit', ['posts']),
methods: {
...mapActions('subreddit', ['createPost']),
async onCreatePost() {
if (this.post.title && (this.post.description || this.post.URL)) {
await this.createPost(this.post);
}
},
},
};
</script>

这是写入createPost((的存储目录中的子reddit.js,在操作中,

import db from '@/db';
const posts = db.collection('posts');
const state = {
posts: [],
};
const actions = {
async createPost(post) {
console.log(post); // eslint-disable-line no-console
const result = posts.doc();
post.id = result.id; // eslint-disable-line no-param-reassign
await posts.doc(post.id).set(post);
},
};
export default {
namespaced: true,
state,
actions,
};

createPost(post)console.log(post)输出太长,但这就是:

{getters: {…}, state: {…}, rootGetters: {…}, dispatch: ƒ, commit: ƒ, …}
commit: ƒ (_type, _payload, _options)
dispatch: ƒ (_type, _payload, _options)
getters: {}
id: "VassMHMvvK2UlfS79bDp"
rootGetters: {}
rootState: {__ob__: Observer}
state: {__ob__: Observer}
__proto__: Object

错误是什么,我无法调试它。

set()函数的第一个参数应为"文档的字段和值的映射",如文档中所述。

从您的问题中,您传递的对象似乎不遵守此约束。

{getters: {…}, state: {…}, rootGetters: {…}, dispatch: ƒ, commit: ƒ, …}
commit: ƒ (_type, _payload, _options)
dispatch: ƒ (_type, _payload, _options)
getters: {}
id: "VassMHMvvK2UlfS79bDp"
rootGetters: {}
rootState: {__ob__: Observer}
state: {__ob__: Observer}
__proto__: Object

这正是错误消息所指示的内容:DocumentReference.set() called with invalid data

因此,您应该调整对象,使其成为文档的字段和值的映射。

例如:

const obj = {foo: 'bar', bar: 'foo'};
await posts.doc(post.id).set(obj);

我已经解决了这个问题。出于某种原因,即使集合中的属性没有明确定义为"必需",除非将完整的对象传递给firestore数据库,否则后期操作也不会起作用。我可能错了,但在尝试了所有的东西都失败了,并决定继续对项目进行编码后,错误就消失了。如果您需要查看,可以在我的GitHub上获得该代码。谢谢你的帮助。

最新更新