为何Axios返回wrap函数?如何在其中使用Axios.CancelToken?
Hey there! Let's tackle your two Axios issues one by one, starting with why you're seeing that wrap function, then how to fix it so you can use CancelToken properly.
1. Why is Axios returning a wrap function?
The root cause here is in your request interceptor. Axios requires that every request interceptor callback returns the config object (or a Promise that resolves to the config). In your code:
instance.interceptors.request.use( function(config) { console.log(instance); // ❌ Missing return statement for config! } );
When you don't return config, the interceptor returns undefined instead. Axios's internal logic interprets this as a failed interception, and it falls back to an internal wrap function (part of its error handling flow) instead of proceeding with the normal request pipeline. That's why you're seeing that unexpected wrap function.
2. Why can't you use Axios.CancelToken in this scenario?
Since your interceptor isn't passing the config object through, any attempt to attach a CancelToken to the request will fail—because the token needs to be part of the config that gets passed along the request chain. Without a valid config being returned from the interceptor, Axios can't process the CancelToken at all.
Fixed Code Example
Here's how to adjust your code to fix both issues, plus an example of using CancelToken:
import axios from "axios"; const instance = axios.create({ baseURL: appUrl, timeout: 0, }); // ✅ Fixed request interceptor: returns config instance.interceptors.request.use( function(config) { console.log(instance); return config; // Don't forget this critical line! }, function(error) { // Optional: handle request errors here return Promise.reject(error); } ); // Export your fixed instance export const $axios = instance; // Example of using CancelToken with your instance (in another file) const CancelToken = axios.CancelToken; const source = CancelToken.source(); // Attach cancel token to request config $axios.get('/your-target-endpoint', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled:', thrown.message); } else { // Handle other request errors } }); // Cancel the request later (e.g., on a button click) source.cancel('Operation canceled by user action.');
Key Takeaways
- Always return the
configobject from your request interceptors (or a Promise that resolves to it) to keep the request pipeline intact CancelTokenrelies on being attached to the requestconfig, so a valid interceptor chain is mandatory for it to work- Adding an error handler to your interceptor is a good practice to catch unexpected issues early
内容的提问来源于stack exchange,提问作者Harsha Murupudi

