将Nuxt Axios响应分配给变量更改响应数据内容


async fetch() {
try {
console.log(await this.$api.events.all(-1, false)); // <-- First log statement
const res = await this.$api.events.all(-1, false); // <-- Assignment
console.log(res); // <-- Second log statement
if (!this.events) {
this.events = []
}
res.data.forEach((event, index) => {
const id = event.hashid;
const existingIndex = this.events.findIndex((other) => {
return other.hashid = id;
});
if (existingIndex == -1) {
this.events.push(events);
} else {
this.events[existingIndex] = event;
}
});
for (var i = this.events.length - 1; i >= 0; --i) {
const id = this.events[i].hashid
const wasRemoved =
res.data.findIndex((event) => {
return event.hashid == id
}) == -1
if (wasRemoved) {
this.events.splice(i, 1)
}
}
this.$store.commit('cache/updateEventData', {
updated_at: new Date(Date.now()),
data: this.events
});
} catch (err) {
console.log(err)
}
}
// The other functions, maybe this somehow helps
async function refreshTokenFirstThen(adminApi, func) {
await adminApi.refreshAsync();
return func();
}
all(count = -1, description = true) {
const func = () => {
return $axios.get(`${baseURL}/admin/event`, {
'params': {
'count': count,
'description': description ? 1 : 0
},
'headers': {
'Authorization': `Bearer ${store.state.admin.token}`
}
});
}
if (store.getters["admin/isTokenExpired"]) {
return refreshTokenFirstThen(adminApi, func);
}
return func();
},

两个日志语句给出的结果略有不同,尽管预期的结果相同。但只有当在这个特定组件中使用函数时,才会发生这种情况。当在其他组件中使用相同的功能时,一切都会按预期进行。

第一个数据输出:

[
{
"name": "First Name",
"hashid": "VQW9xg7j",
// some more correct attributes
},
{
"name": "Second name",
"hashid": "zlWvEgxQ",
// some more correct attributes
}
]

而第二个console.log给出以下输出:

[
{
"name": "First Name",
"hashid": "zlWvEgxQ",
// some more correct attributes, but this time with reactiveGetter and reactiveSetter
<get hashid()>: reactiveGetter()
​​        length: 0
​​​​        name: "reactiveGetter"
​​​​        prototype: Object { … }
​​​​<prototype>: function ()
​​​<set hashid()>: reactiveSetter(newVal)
​​​​length: 1
​​​​name: "reactiveSetter"
​​​​prototype: Object { … }
​​​​<prototype>: function ()
},
{
"name": "Second name",
"hashid": "zlWvEgxQ",
// some more correct attributes and still without reactiveGetter and reactiveSetter
}
]

可以看出,在分配函数调用的响应时,我的hashid属性的值会以某种方式发生变化。

这里发生的下一个奇怪行为是,hashid字段发生变化的第一个对象也得到了reactiveGetterreactiveSetter(但数组中的第二个对象没有得到这些(。

所以在我看来,这项任务发生了一些我不知道的事情。另一种猜测是,这与Vuex商店有关,因为我不会在使用相同功能的其他地方更改Vuex商店。

经过验证,后端总是发送正确的数据,因为这是伪数据,由一个包含两个具有某些属性的对象的数组组成。因此,除了这两个对象之外,不需要其他数据。

有人能向我解释为什么会发生这种行为吗?

有几个问题。。。

  1. 不要将console.log与对象一起使用。浏览器倾向于显示";实时视图";对象参考

  2. this.events.findIndex((other) => { return other.hashid = id; });是错误的,您使用的是赋值运算符(=(而不是标识运算符(===(。这就是为什么第一个元素的hashid会发生变化。。。

最新更新