前言:
最近打算用vue 写个音乐播放器,在搞 vuex 的时候遇到一个很神奇报错;vuex 姿势练了千百次了,刚开始的时候我一直以为是代码问题,反复检查了带了,依旧报错。 Error in mounted hook: "TypeError: Cannot read properties of undefined (reading 'getters')"
除了 mapGetters 中的 方法 都能把数据都正确,连 mapMutations 中的方法都是对的。
按理说 mapMutations 可以,mapGetters 也应该可以才对!
<script> import { mapGetters, mapMutations } from "vuex"; export default { data() { return {}; }, computed: { ...mapGetters({ userInfo: "userInfo", }), userInfo1() { return this.$stroe.state.userInfo; }, }, mounted() { console.log("this.$stroe:", this.$stroe); console.log("this.$stroe.mapGetters:", this.$stroe.mapGetters); console.log("this.$stroe.getters:", this.$stroe.getters); console.log("this.$stroe.state.userInfo:", this.$stroe.state.userInfo); console.log("this.userInfo1:", this.userInfo1); console.log("this.saveToken:", this.saveToken); console.log("this.userInfo:", this.userInfo); }, methods: { ...mapMutations({ saveToken: "saveToken", }), }, }; </script> 输出 store: {…} this.$stroe: Store {_committing: false, _actions: {…}, _actionSubscribers: Array(0), _mutations: {…}, _wrappedGetters: {…}, …}commit: ƒ boundCommit(type, payload, options)dispatch: ƒ boundDispatch(type, payload)getters: {}strict: false_actionSubscribers: []_actions: {loadStorage: Array(1), cleanStorage: Array(1)}_committing: false_devtools: undefined_makeLocalGettersCache: {}_modules: ModuleCollection {root: Module}_modulesNamespaceMap: {}_mutations: {saveToken: Array(1), updateToken: Array(1), saveUserinfo: Array(1), updateUserInfo: Array(1)}_scope: EffectScope {detached: true, active: true, effects: Array(2), cleanups: Array(0), parent: undefined}_state: {__ob__: Observer}_subscribers: []_wrappedGetters: {userInfo: ƒ, token: ƒ}state: (…)[[Prototype]]: Object this.$stroe.mapGetters: undefined this.$stroe.getters: {} this.$stroe.state.userInfo: {…} this.userInfo1: {…} this.saveToken: ƒ mappedMutation() { var args = [], len = arguments.length; while (len--) args[len] = arguments[len]; // Get the commit method from store var commit = this.$store.commi…
解决:
各种姿势都试了,这次不知道啥情况。代码也检查了;项目重启了, 电脑也重启了。 磨了很长时间 最后试了下 换了个 vuex 版本就然可以了 ! 最后才发现 原来是 引用的 vuex 4.1.0, 版本回退到 3.6.2 就可以了 ,给大家填个坑