2

我最近迁移到Vuex商店,我取得了相当大的进步。但我目前面临的挑战是从 Vuex 的另一个动作中调用一个动作。我还在学习 Vue.js

Current versions

  1. Vue 3
  2. Vuex 4
  3. 如果需要,我使用Electron Vue.js dev tools

/src/store/index.js- 当前代码

/* eslint-disable no-redeclare */

import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    ...
  },
  mutations: {
    setQuery(state, query) {
      // refers this.state.query
      state.query = query
    },

    setOnlinePresenceInitialPageLoad(state, presence) {
      // refers this.state.online & this.state.initialPageLoad
      state.online = presence
      state.initialPageLoad = false
    },

    setRequestErrorAndStatus(state, { _status, code }) {
      // refers this.state.request.error & this.state.request._status
      state.request.error = _status
      state.request._status = code
    },

    setResults(state, processed) {
      state.request.results = processed
    }
  },
  actions: {
    callApi({ commit, state, dispatch }) {
      axios.get(state.axios.targetURL, {
        baseURL: state.axios.config.baseURL,
        params: {
          days: state.axios.config.params.days,
          q: state.query,
          key: state.axios.config.params.key,
        },
      }).then(response => {
        console.log(response.status)
        commit('setOnlinePresenceInitialPageLoad', true);
        dispatch('formatResults', response.data);
      }).catch(error => {
        if (error.response) {
          console.log(error.response.status)
        } else if (error.request) {
          console.log(error.request.status)
        } else {
          console.log("Couldn't find the problem")
        }
      })
    },
    formatResults(context, payload) {
      const processedData = {
          ...
      }
      console.log(processedData);
      context.commit('setResults', processData);
    }
  },
  modules: {
  }
})

正如您在 Promise 的已完成部分中看到的callApi()调用。formatResults()

Current state (Web browser)

Web 浏览器控制台中的当前状态

在代码中,我尝试注销变量processedData。我以为它会打印在控制台上。

Current state (Vue Devtools)

Vue.js 开发工具中的当前状态

我也想知道为什么formatResults()永远不会结束。

这个问题可以用异步函数解决吗,如果是,那么我想知道要采取的程序吗?

谢谢您的帮助

4

1 回答 1

2

很难从提供的信息中分辨出来,但我会在这里冒险猜测......

看到它console.log(response.status)然后console.log("Couldn't find the problem")被触发,以及formatResults(来自 vuex 屏幕截图)我怀疑这formatResults会引发错误。

formatResults(context, payload) {
  const processedData = {
      // the error could be somewhere here
  }
  console.log(processedData);
  context.commit('setResults', processData);
}

当错误发生时,catch将处理它

if (error.response) {
  console.log(error.response.status)
} else if (error.request) {
  console.log(error.request.status)
} else {
  // handled here with log ...
  console.log("Couldn't find the problem")
}

尝试使用console.error(error)以查看错误的原因是什么

if (error.response) {
  console.log(error.response.status)
} else if (error.request) {
  console.log(error.request.status)
} else {
  console.error(error)
}

然后你可能有足够的信息来调试问题的根源

于 2021-12-22T20:00:49.623 回答