【问题标题】:TypeError: Cannot read property 'cache' of undefined - VueJSTypeError:无法读取未定义的属性“缓存”-VueJS
【发布时间】:2019-11-26 15:04:35
【问题描述】:

我创建了一个导出异步函数的 Vue 组件。该组件充当调用我的 API 的包装器。它基于 axios 和一个 caching 组件,该组件依赖于 localforage 以获得一些短暂的持久性。

import localforage from 'localforage'
import memoryDriver from 'localforage-memoryStorageDriver'
import { setup } from 'axios-cache-adapter'

export default {
    async cache() {
        // Register the custom `memoryDriver` to `localforage`
        await localforage.defineDriver(memoryDriver)

        // Create `localforage` instance
        const store = localforage.createInstance({
            // List of drivers used
            driver: [
                localforage.INDEXEDDB,
                localforage.LOCALSTORAGE,
                memoryDriver._driver
            ],
            // Prefix all storage keys to prevent conflicts
            name: 'tgi-cache'
        })

        // Create `axios` instance with pre-configured `axios-cache-adapter` using a `localforage` store
        return setup({
            // `axios` options
            baseURL: 'https://my.api',
            cache: {
                maxAge: 2 * 60 * 1000,          // set cache time to 2 minutes
                exclude: { query: false },      // cache requests with query parameters
                store                           // pass `localforage` store to `axios-cache-adapter`
            }
        })
    }
}

这是我在视图中导入和使用此组件的方式:

import api from '@/components/Api.vue'

export default {
    data() {
        return {
            userId: this.$route.params.id,
            userData: ''
        }
    },
    methods: {
        loadClient(userId) {
            const thisIns = this;
            api.cache().then(async (api) => {
                const response = await api.get('/client/find?id='+userId)
                thisIns.userData = response.data.data[0]
            }).catch(function (error) {
                console.log(error)
            })
        },
    },
    created() {
        this.loadClient(this.userId)
    },
}

我可以导入这个组件,一切似乎都可以正常工作。我从我的 API 中取回数据。但是,每次通话后,我都会立即收到错误消息:

TypeError: 无法读取未定义的属性“缓存”

引用此行:

api.cache().then(async (api) => {

我无法理解为什么会发生这种情况,或者这意味着什么。错误本身表明我正在导入的组件未定义,但显然不是这样;如果是这样,我怀疑 API 调用最终会失败。相反,我相信我可能没有正确构建/导出我的 async cache() 函数。

【问题讨论】:

  • 放入一些控制台日志或debugger 语句以确认api 不是undefined 并且确实具有预期的cache 方法。如果您看到请求转到服务器,则要么api.cache() 被正常调用,要么其他东西正在发出该请求。当您说它引用该行时,它是具体说明该行导致错误还是只是堆栈跟踪中的行之一?
  • 这不应该是相关的,但是......将那个api作为一个vue组件背后的原因是什么?如果您根本不将它用作 vue 组件,甚至不使用 mixin。这应该是一个普通的 js 文件,在最好的情况下,我会将它转换为 Vue 插件。除此之外,adapter docs 导出异步函数而不包装它。试试导出export default async cache() ...

标签: vue.js async-await


【解决方案1】:

经过进一步审查,我实际上不明白为什么 author has implemented 会这样。为什么要在每次进行 API 调用时都创建一个 localForage 实例?

我选择不使用组件,只实例化一次 localForage 实例。

ma​​in.js

import localforage from 'localforage'
import memoryDriver from 'localforage-memoryStorageDriver'
import { setup } from 'axios-cache-adapter'

// Register the custom `memoryDriver` to `localforage`
localforage.defineDriver(memoryDriver)

// Create `localforage` instance
const localforageStore = localforage.createInstance({
    // List of drivers used
    driver: [
        localforage.INDEXEDDB,
        localforage.LOCALSTORAGE,
        memoryDriver._driver
    ],
    // Prefix all storage keys to prevent conflicts
    name: 'my-cache'
})

Vue.prototype.$http = setup({
    baseURL: 'https://my.api',
    cache: {
        maxAge: 2 * 60 * 1000,          // set cache time to 2 minutes
        exclude: { query: false },      // cache requests with query parameters
        localforageStore                // pass `localforage` store to `axios-cache-adapter`
    }
})

视图

export default {
    data() {
        return {
            userId: this.$route.params.id,
            userData: ''
        }
    },
    methods: {
        loadClient(userId) {
            const thisIns = this;
            thisIns.$http.get('/client/find?id='+userId)
                .then(async (response) => {
                    thisIns.userData = response.data.data[0]
                })
                .catch(function (error) {
                    console.log(error)
                })
        },
    },
    created() {
        this.loadClient(this.userId)
    },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 2021-12-08
    • 2021-02-27
    • 1970-01-01
    • 2020-11-08
    • 2017-09-16
    • 2020-08-27
    • 2021-12-28
    相关资源
    最近更新 更多