首页 > 解决方案 > 在操作中发送发布请求并使用 vuex 提交数据更改

问题描述

boolean在提交新用户后,我尝试将 a 设置为 true,vuex但出现了一个奇怪的错误Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

这是中的创建方法actions state

        async CREATE_USER({state}) {
                await axios.post('api/user', state.user)
                        commit('SET_CREATED_USER');
        },

这是突变

 SET_CREATED_USER: (state) => {
            state.newUserCreated = true;
            console.log('user create? -> ', state.newUserCreated);
        }

和 on submit 方法

onSubmit() {
              this.$store
                  .dispatch('CREATE_USER')
                  .then(() => {
                      this.inProgress = false;
                      // navigate to user
                      this.$router.push('users');
                  })
                  .catch( ({ response }) => {
                      this.inProgress = false;
                      this.errors = response.data.errors;
                      console.log('you have an error on creating an user')
                    });
            },

我试图添加.thenCREATE_USER方法

axios.post('api/user', state.user).then(
() => commit('SET_CREATED_USER');
)

得到了同样的错误我也试过

async CREATE_USER({state}, context) {
                await axios.post('api/user', state.user)
                        context.commit('SET_CREATED_USER');
        },

我也尝试删除async,但出现错误

Uncaught (in promise) ReferenceError: commit is not defined

标签: vue.jsaxioshttp-postvuexcommit

解决方案


两个问题:

  1. 您正在尝试commit在您的操作中使用而无法访问它
async CREATE_USER({ state, commit }) {
    await axios.post('api/user', state.user)
    commit('SET_CREATED_USER');
},
  1. 您正在尝试访问response.data.errorsresponse它是一个可为空的键,因此它会引发错误。您可能只使用可选链接来处理它。
.catch((error) => {
    this.inProgress = false;
    this.errors = error?.response?.data?.errors
    console.log('you have an error on creating an user')
});

推荐阅读