【问题标题】:sent a post request in actions and commit a data change with vuex在操作中发送发布请求并使用 vuex 提交数据更改
【发布时间】:2020-07-10 19:46:21
【问题描述】:

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

这是actionsstate中的create方法

        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')
                    });
            },

我尝试将.then 添加到CREATE_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.js axios http-post vuex commit


    【解决方案1】:

    两个问题:

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

    【讨论】:

    • @key 您在浏览器控制台中看到错误吗?您在网络标签中看到 http 请求了吗?
    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    相关资源
    最近更新 更多