Vue3中Axios错误回调失效:errorCallback不是函数问题求助
问题分析与解决方案
报错TypeError: errorCallback is not a function的核心原因是:当Axios请求进入catch分支时,errorCallback未被正确传入(或传入的值不是函数),同时原代码未对errorCallback的合法性做校验。结合你的代码,以下是具体修复方案:
1. 修复useFetch函数
将原有的then/catch改为async/await + try/catch写法,同时给errorCallback设置默认空函数,避免未传入时报错:
// composables/fetch.js import axios from "axios"; export async function useFetch(method, route, params = {}, data = {}, callback, errorCallback = () => {}) { const baseUrl = import.meta.env.VITE_BASE_URL; const username = import.meta.env.VITE_ADMIN_USER; const password = import.meta.env.VITE_ADMIN_PASSWORD; const url = `${baseUrl}/endpoint/${route}`; try { const res = await axios({ method, url, auth: { username, password }, data, params }); // 使用可选链调用,防止callback未传入时报错 callback?.(res); return res; } catch (error) { errorCallback(error); // 抛出错误,允许调用方通过try/catch进一步处理 throw error; } }
- 给
params和data设置默认空对象,简化调用时的参数传递 - 用
try/catch替代Promise链,代码逻辑更清晰 - 给
errorCallback设置默认空函数,彻底避免"不是函数"的报错
2. 修正组件中的错误回调写法
在changeFactorListData中,错误回调的解构写法有误(Axios的catch参数是完整错误对象,没有单独的err属性),直接传递onFetchError即可:
<script setup> import {ref} from 'vue' import {useFetch} from "@/composables/fetch.js"; const factorData = ref([]); // 补充定义totalItems,避免成功回调中报错 const totalItems = ref(0); function getFactorListData() { useFetch('get', `factor/${props.apiRoute}`, {}, {}, ({data}) => { console.log('data: ', data); factorData.value = data; totalItems.value = data.length; }, (err) => { console.log('err: ', err); }) } function changeFactorListData(factor) { // 直接传入onFetchError,无需额外包装 useFetch('put', `factor/${props.apiRoute}/${factor.id}`, {}, factor, getFactorListData, onFetchError); } function onFetchError(err) { console.log('error: ', err); } </script>
- 补充定义了
totalItems,避免成功回调中因变量未定义抛出错误(该错误会被useFetch的catch捕获,可能干扰错误回调的排查) - 简化错误回调的传递方式,避免不必要的箭头函数包装
3. 可选优化:改用对象参数传递(避免顺序错误)
如果担心参数顺序搞错,可以将useFetch改为接收对象参数的形式,进一步提升代码健壮性:
// composables/fetch.js export async function useFetch({ method, route, params = {}, data = {}, callback, errorCallback = () => {} }) { const baseUrl = import.meta.env.VITE_BASE_URL; const username = import.meta.env.VITE_ADMIN_USER; const password = import.meta.env.VITE_ADMIN_PASSWORD; const url = `${baseUrl}/endpoint/${route}`; try { const res = await axios({ method, url, auth: { username, password }, data, params }); callback?.(res); return res; } catch (error) { errorCallback(error); throw error; } } // 组件中调用方式 useFetch({ method: 'get', route: `factor/${props.apiRoute}`, callback: ({data}) => { factorData.value = data; totalItems.value = data.length; }, errorCallback: (err) => console.log('err: ', err) });
内容的提问来源于stack exchange,提问作者yangsunny
相关产品推荐
相关产品推荐

