如何在setTimeout的dispatch中传递带参数函数?Redux-thunk代码排错
Let's walk through the issues in your code and fix them one by one to get the delayed dispatch working correctly:
1. Invalid Syntax for mock_Response
Your current mock response definition [key="A",value="xyz"] isn't valid JavaScript. If you're trying to create a key-value pair, use an object literal instead:
const mock_Response = { key: "A", value: "xyz" };
If you intended an array of values, it would be ["A", "xyz"], but based on how you're passing it to actions.success, an object makes more sense here.
2. Unresolved clientRequest() Call
You're calling dispatch(clientRequest()), but there's no definition for clientRequest in your code. Since you already generate action creators from your types array with typesToActionCreators, you should use the generated request action instead:
dispatch(actions.request());
This was likely throwing a ReferenceError: clientRequest is not defined error, which would break the entire flow.
3. Fragile Error Handling
Using the second parameter of then() for error handling works, but it doesn't catch errors thrown in subsequent then() blocks, and it returns undefined to the next chain, which can lead to unexpected behavior. Switch to using a catch() block instead, and make sure to dispatch the failure action to update your Redux state:
.catch(error => { console.error('An error occurred:', error); dispatch(actions.failure(error)); throw error; // Re-throw if you want the caller to handle the error too });
4. Optional: Track the Delayed Dispatch (For Testing/Async Coordination)
Right now, your thunk returns the axios promise, but the delayed dispatch inside setTimeout isn't tracked. If you need to wait for that dispatch to complete (e.g., in tests), wrap the setTimeout in a Promise:
return new Promise(resolve => { setTimeout(() => { dispatch(actions.success(mock_Response, dataKey)); resolve(); }, 4000); });
Full Corrected Code
export const fetchActionCreator = ({ types, url, fetchOptions, dataKey }) => dispatch => { const actions = typesToActionCreators(types); dispatch(actions.request()); // Fixed mock response syntax const mock_Response = { key: "A", value: "xyz" }; return axios.get(url, fetchOptions) .then(response => response.data) .then(data => { console.log('time Before ' + new Date()); // Wrap setTimeout in Promise for optional async tracking return new Promise(resolve => { setTimeout(() => { dispatch(actions.success(mock_Response, dataKey)); resolve(); }, 4000); }); console.log('time After ' + new Date()); }) .catch(error => { console.error('An error occurred:', error); dispatch(actions.failure(error)); throw error; }); }; function typeToActionCreator(type) { return typeof type === 'function' ? type : (payload, dataKey) => ({ type, payload, dataKey }); } function typesToActionCreators(types) { const [request, success, failure] = types.map(typeToActionCreator); return { request, success, failure }; }
Make sure your types argument is an array with three elements (in order: request action type, success action type, failure action type) so typesToActionCreators can generate the correct action creators.
内容的提问来源于stack exchange,提问作者Shrikant Dande

