【问题标题】:Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '$get') when using axios in onAuthStateChangedUncaught (in promise) TypeError: Cannot read properties of undefined (reading '$get') when using axios in onAuthStateChanged
【发布时间】:2022-01-06 09:56:42
【问题描述】:

我想在我的 VueX 商店中的 onAuthStateChanged 钩子之后执行 axios 请求:

export const actions = {
  async onAuthStateChanged({ commit }, { authUser }) {
    if (authUser) {
      const test = await this.$axios.$get("/api/v1/products");
      console.log(test);
      const { uid, email } = authUser;
      commit("setUser", { uid, email });
      Cookies.set("auth-status", "authorized");
    } else {
      commit("cleanUser");
      Cookies.remove("auth-status");
    }
  },
  async login(_, { email, password }) {
    try {
      await this.$fire.auth.signInWithEmailAndPassword(email, password);
    } catch (error) {
      throw error.message;
    }
  },

然而,这给了我一个

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '$get')

在另一个 VueX 存储模块中,我使用相同的方式调用我的 axios 请求:

export const actions = {
  async fetchAllProducts({ commit }) {
    try {
      const products = await this.$axios.$get("/api/v1/products");
      commit("setProducts", products);
    } catch (error) {
      console.log(error);
    }
  },
}  

效果很好。这让我转向 onAuthStateChanged 钩子由于某种原因不接受 axios。

【问题讨论】:

  • 问题可能不在此处。您是否在nuxt.config.js 中检查过您的模块? onAuthStateChanged 是一个 Vuex 动作,对吧?
  • @kissu,没有 onAuthStateChanged 是一个 firebase 钩子:firebase.google.com/docs/reference/js/v8/…
  • 它到底在哪里?那里有 Nuxt 上下文吗?
  • 您确定不是要使用$axios(来自解构参数)而不是this.$axios
  • @samthecodingman 最后是一样的。至少,我怀疑 onAuthStateChanged 是否像 asyncData 一样工作,没有 Nuxt 上下文又名 this

标签: firebase firebase-authentication nuxt.js vuex


【解决方案1】:

我认为您在下面的行中将 $axios 作为 函数参数 传递:

async onAuthStateChanged({ commit, $axios }, { authUser }) {

在下面的行中,$axios 可以被引用为 上下文变量,因此会出现错误

const test = await this.$axios.$get("/api/v1/products");

要解决此问题,请将其修改为:

const test = await $axios.$get("/api/v1/products");

【讨论】:

  • 检查我对问题的编辑
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 2022-10-09
  • 2022-07-21
  • 2022-07-22
  • 2022-10-13
  • 2022-01-07
  • 2022-10-18
  • 2022-06-13
相关资源
最近更新 更多