【发布时间】:2019-09-12 06:07:50
【问题描述】:
我正在使用 Vuex 的“操作”通过 API 从我的数据库中获取数据。
效果很好,我有一个console.log(jsonResponse),它显示了正确的数据。
但是,当我将commit('updateQuestions', jsonResponse) 添加到图片时,所有字段的返回值都是"Setters & Getters"
store.js:
mutations: {
updateQuestionsInit: (state, payload) => {
state.questions.init = payload
}
},
actions: {
onInit: async ({commit}) => {
try {
let response = await fetch('http://localhost:8080/api/mongo/initialforms')
if (response.ok) {
let jsonResponse = await response.json()
console.log(jsonResponse)
// Omitting the below line means it works.
commit('updateQuestionsInit', jsonResponse)
}
}
catch (error) {
console.log('ERROR', error)
}
}
}
结果
预期结果
[
{
id: 0,
type: "dropdown",
value: "sku",
}, ...
]
实际结果
[
{
id: Getter & Setter,
type: Getter & Setter
value: Getter & Setter,
…
}, ...
]
为什么会发生这种情况以及如何纠正?
【问题讨论】:
-
“所有字段的返回值都是“Setters & Getters”是什么意思?你在哪里看结果?这是来自
console.log(jsonResponse)代码行吗? -
commit()函数是否修改了它传递的jsonResponse对象?如果是这样,那么这可能是console.log(jsonResponse)直到commit()已经修改它之后才实际记录对象的问题。你可以通过console.log(JSON.stringify(jsonResponse))来测试这个理论。 -
@jfriend00 是的,没错。
-
@jfriend00 我刚刚尝试了您的故障排除。
JSON.stringify()按预期通过它。一旦它发生突变,我使用JSON.parse()将它改回来,它仍然发生。Setters & Getters的这些属性现在处于我的状态,而不是实际值 -
嗯,这显然是因为
commit()正在修改您的对象。去看看那个代码,而不是这个代码。这就是它被修改的地方。根据您目前显示的代码,我们没有其他建议。
标签: asynchronous vue.js promise action vuex