TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]()

TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]()

阅读本期的朋友们大家好。我将 Vue 2 与 firebase 一起使用。我想获取包含对象的数组列表。该列表从 firebase 实时数据库成功获取,但问题是当我想将这个数组存储到 Vuex 状态时,我得到了这个错误

TypeError:解构不可迭代实例的尝试无效。为了可迭代,非数组对象必须有一个 Symbol.iterator

这是我从 firebase 实时数据库获取数据的代码

 getAllProject() {
    //var result = [];
    var userId = store.state.user.user.uid;
    var project_ref = database.ref("projects/" + userId + "/");
    project_ref.on("value", function(snapshot) {
      if (snapshot.hasChildren) {
        snapshot.forEach(function(DataSnapsho) {
          try {
            store.dispatch("projects/set_poject", DataSnapsho.val());
          } catch (error) {
            console.log(error);
          }
        });
      }
    });
  }

这是我的 Vuex 代码 export const namespaced = true;

export const state = {
  test: []
};

export const mutations = {
  SET_PROJECT(state, paylod) {
    state.test.push(paylod);
  }
};

export const actions = {
  set_poject([commit], paylod) {
    commit("SET_PROJECT", paylod);
  }
};

这是我调用 getAllProject 方法的地方

     mounted() {
    read_project.getAllProject();
  },

输出错误是这样的

TypeError: Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
    at _nonIterableRest (nonIterableRest.js?3d8c:2)
    at _slicedToArray (slicedToArray.js?3835:6)
    at Store.set_poject (projects.js?f817:296)
    at Array.wrappedActionHandler (vuex.esm.js?2f62:851)
    at Store.dispatch (vuex.esm.js?2f62:516)
    at Store.boundDispatch [as dispatch] (vuex.esm.js?2f62:406)
    at eval (readProject.js?72b9:18)
    at eval (index.esm.js?e947:4417)
    at LLRBNode.inorderTraversal (index.esm.js?e947:2769)
    at SortedMap.inorderTraversal (index.esm.js?e947:3219)

实际数组是这样的

问题出在你的这行代码上:

set_poject([commit], paylod) {
    commit("SET_PROJECT", paylod);
  }

实际上 commit 在对象内部,您 不能将对象解构为数组 。因此,当您尝试这样做时,它会给出错误 destructure non-iterable instance.

像这样更新代码:

set_poject({commit}, paylod) {
    commit("SET_PROJECT", paylod);
  }