无法从服务器获取数据至NuxtJS Store问题求助
Hey there, let's break down what's going wrong and get your store working properly step by step:
1. Incorrect Actions Definition
The biggest blocker here is how you’ve defined your actions—you wrapped them in an arrow function that returns an object, but Nuxt expects actions to be a plain object directly. This breaks the context (like access to this.$axios and the commit helper), so your action never runs as intended.
2. Mutation Naming Mismatch (Optional but Critical for Readability)
Your mutation is named SET_IP, but it’s actually responsible for storing product data. Renaming it to something semantic like SET_PRODUCTS will make your code easier to maintain and debug later.
3. Add Error Handling (Best Practice)
Wrapping your API call in a try/catch block will help you debug if there’s an issue with the server response, even if the server itself is running.
Corrected Store Code
export const state = () => ({ products: [] }); export const getters = { getProducts: state => state.products }; export const mutations = { SET_PRODUCTS: (state, payload) => { state.products = payload; } }; export const actions = { async getProducts({ commit }) { try { const products = await this.$axios.$get("http://localhost:8080/products"); commit("SET_PRODUCTS", products); } catch (error) { console.error("Error fetching products:", error); // Optional: Commit an error state here if you want to handle it in your UI } } };
Testing the Fix
To confirm the data is being stored correctly, dispatch the action from a component (e.g., in the mounted hook):
export default { async mounted() { await this.$store.dispatch('getProducts'); // Log the products to verify they’re in the store console.log("Fetched products:", this.$store.getters.getProducts); } }
Also, double-check that you have the @nuxtjs/axios module properly installed and configured in your nuxt.config.js (make sure it’s listed in the modules array).
内容的提问来源于stack exchange,提问作者oussema sallemi

