React-Redux项目调用TheMealDB API失败,请求技术协助
解决React-Redux调用TheMealDB API的问题
问题核心原因
你遇到的failed to fetch API和net::ERR_INSUFFICIENT_RESOURCES错误,主要是因为createAsyncThunk的回调函数没有正确返回Promise,也未将错误传递给Redux Thunk的处理流程。同时代码中导入了axios却未实际使用,存在冗余。
修复方案
方案1:规范使用Fetch API
修改fetchRecipes逻辑,确保返回Promise并正确抛出异常,让Redux Thunk能捕获并处理状态:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; export const fetchRecipes = createAsyncThunk( 'recipes/fetchRecipes', async () => { const response = await fetch('https://www.themealdb.com/api/json/v1/1/list.php?c=list'); if (!response.ok) { throw new Error('请求失败'); } const data = await response.json(); console.log(data); return data; } ); const recipesSlice = createSlice({ name: 'recipes', initialState: { recipes: [], status: 'idle', error: null, }, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchRecipes.pending, (state) => { state.status = 'loading'; }) .addCase(fetchRecipes.fulfilled, (state, action) => { state.status = 'succeeded'; state.recipes = action.payload.meals; // API返回的列表数据在meals字段中 }) .addCase(fetchRecipes.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message; }); }, }); export default recipesSlice.reducer;
方案2:使用Axios简化请求
既然已经导入了axios,可以直接用它处理请求,自动完成JSON解析和错误捕获:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; import axios from 'axios'; export const fetchRecipes = createAsyncThunk( 'recipes/fetchRecipes', async () => { const response = await axios.get('https://www.themealdb.com/api/json/v1/1/list.php?c=list'); console.log(response.data); return response.data; } ); const recipesSlice = createSlice({ name: 'recipes', initialState: { recipes: [], status: 'idle', error: null, }, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchRecipes.pending, (state) => { state.status = 'loading'; }) .addCase(fetchRecipes.fulfilled, (state, action) => { state.status = 'succeeded'; state.recipes = action.payload.meals; }) .addCase(fetchRecipes.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message; }); }, }); export default recipesSlice.reducer;
额外排查点
如果修复代码后仍出现ERR_INSUFFICIENT_RESOURCES错误,检查是否存在重复调用fetchRecipes的情况(比如组件重复渲染导致多次请求),可以通过useEffect添加合适的依赖项控制请求触发时机。
内容的提问来源于stack exchange,提问作者Harshika Govind
相关产品推荐
相关产品推荐

