vue.js - 在操作中发送发布请求并使用 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')
});
},
我试图添加.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
解决方案
两个问题:
- 您正在尝试
commit
在您的操作中使用而无法访问它
async CREATE_USER({ state, commit }) {
await axios.post('api/user', state.user)
commit('SET_CREATED_USER');
},
- 您正在尝试访问
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')
});
推荐阅读
- webrtc - android问题中的多个对等连接Web-RTC
- python - 有没有办法自动加入来自同一组的具有相同值的列表?
- ibm-mq - IBM MQ SDK 取决于客户端
- java - 从不同的 Activity 返回到特定的 Fragment
- javascript - 将 textarea 的内容推送到数组中
- python-3.x - ImportError:请从 https://www.github.com/nvidia/apex 安装 apex 以使用分布式和 fp16 训练
- python - 扩展具有附加属性的类时出现 TypeError
- ios - 在 tvOS 上播放时仅出现“MPMediaItemPropertyTitle”,尽管所有其他信息都在控制中心
- php - 在 Netbeans 8.2 中禁用智能缩进
- reactjs - 构建脚本返回非零退出代码:1