关于Hbuilder中使用 vuex-persistedstate 遇到的问题
遇到问题不害怕,无需着急;冷静下来慢慢分析、定位问题。
报错
起因:真机调试运行时报错:
reportJSException >>>> exception function:createInstanceContext, exception:white screen cause create instanceContext failed,check js stack ->Uncaught TypeError: Cannot read property 'setItem' of undefined
这个问题并不会在网页调试、小程序调试中出现,只会在真机调试中出现。单看报错信息也是非常的懵:拿到两个关键词setItem
、undefined
。太模糊了,根本没办法定位。
具体排查过程不详细说了(花费了不少时间最后才定位到时vuex-persistedstate
的问题)。此文主要是总结记录、分享。
看一下报错的写法:
一般开发 网页项目 这样写是不会有问题的。但是 !!!
到了App环境就会出现上面莫名的问题。
问题根源
原因在于
vuex-persistedstate
默认配置是使用window.localStorage
。
为了求证特意去看了源码,仓库地址 vuex-persistedstate
源码也非常少,只有一个index.ts
文件。
// 源码34行:
const storage = options.storage || (window && window.localStorage);
// 源码53行
function setState(key, state, storage) {
return storage.setItem(key, JSON.stringify(state));
}
在栏看看真机运行时候window
是个啥,打印输出:
真机运行时候
window
对象是undefined
。
问题根源找到了~~
解决方法
persistedState
是接收一个 Options
参数的。把 Storage
的参数写一下,用上 uniapp
特有的api
。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//引入vuex-persistedstate
import persistedState from "vuex-persistedstate";
import pricedetail from './pricedetail.js'
console.log(' =====> window', window);
const store = new Vuex.Store({
state: pricedetail.state,
getters: pricedetail.getters,
mutations: pricedetail.mutations,
actions: pricedetail.actions,
plugins: [persistedState({
// 传入参数
storage: {
getItem: (key) => uni.getStorageSync(key),
setItem: (key, val) => uni.setStorageSync(key, value),
removeItem: (key) => uni.removeStorageSync(key)
}
})]
})
export default store
end