重新加载后 Vuex 状态为空

Vuex state empty after reload

在突变中我正在改变我的 state 如:

try {
  const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: 'Bearer ###'
    }
  });

  var obj = cloneDeep(response.data);
  var temp = cloneDeep(response.data.line_items_attributes.nested_form)

  temp = Object.keys(temp).map(key => {
    return {
      ...temp[key]
    }
  });

  obj.line_items_attributes.nested_form = cloneDeep(temp);

  state.form = cloneDeep(obj);
  console.log(state.form);
} catch (error) {
  ...
}

因此 state 应包含一个以对象作为条目的数组。检查 state 也显示相同。它显示在视图上。 现在重新加载时,除数组内的对象外,所有内容都保留在 state 内。它只是在商店中显示一个空数组:

line_items_attributes:
  attribute: "line_items_attributes"
  label: "Positionen"
  model_class: "expense_line_item"
  nested_form: []              // <---- Object is gone

Nested_form是后台下发的hahsmap。我只是把它变成一个数组。 line_items_attribute 是一个 属性 对象存储的状态。 编辑:但如果不进行转换,它也无法正常工作。分配的状态没有得到保留。

store.js

const store = createStore({
    strict: false,
    plugins: [createPersistedState()],
    modules: {
        expense,
        invoice
    }
});

像这样调用 action/mutation:

const updateOuter = (event, refreshable, propertyName) => {
   store.dispatch('expense/updateOuterValue', ({
      refresh: refreshable,
      propertyName: propertyName,
      value: event.target.checked ? 1 : 0
   }))
};

编辑:

在调用突变后更改不同的值时,nested_form 对象在重新加载后被保留。

如果我两次调用突变,它似乎有效...知道这是怎么回事吗?

问题是 axios 在 mutation 中的执行。 Vuex mutation 中必须 没有异步调用。正如@e200

所建议的

You shouldn't do async operations inside mutations, use actions instead.

因此,它不仅仅是一个最佳实践,而是一个必须要做的事情。 此处解释:mutations must be synchronous