首页 > 解决方案 > Vuex + Typescript:突变对象有效载荷始终未定义

问题描述

在运行时,我作为辅助参数传递给我的 Vuex 变异方法的对象有效负载始终是undefined. 我的 Vuex 和组件文件都是用 TypeScript 编写的。

index.ts的 Vuex 商店文件如下所示(请注意,我使用的是模块化商店方法):

import Profile from '@/models/Profile'
import { createStore } from 'vuex'

const userModule = {
  state: () => ({
    profile: Profile
  }),
  mutations: {
    setProfile (state:any, profile: Profile) {
      // `state` is the local module state
      state.profile = profile //**RUNTIME ERROR: profile = undefined
    } 
  },
  getters: {
    getProfile (state:any) {
      return state.profile
    }
  }
}

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    user: userModule
  }
})

我从我的 Vue 组件提交到商店,methods如下所示:

 <script lang="ts">
 export default Vue.extend({
    methods: {
      fetchProfile() {
        axios
            .get("/getUser", requestHeader)
            .then((profileResponse: Profile) => {
              //store profile in Vue Store
              store.commit('setProfile', profileResponse)
            })
      }
    }
 })
 </script>

我究竟做错了什么?

标签: typescriptvue.jsvuexvuex-modules

解决方案


axios.get().then()回调有一个 type 的参数,AxiosResponse它将实际响应包装在其data属性中。代码应如下所示:

import axios, { AxiosResponse } from 'axios'

axios.get(/*...*/)
  .then((response: AxiosResponse) => {
    const profileResponse = response.data
    store.commit('setProfile', profileResponse)
  })

推荐阅读