动作必须是普通对象。使用自定义中间件进行异步操作错误,即使使用 thunk 作为中间件
Actions must be plain objects. Use custom middleware for async actions error eventhough useing thunk as middleWare
我收到这个错误:
"Actions must be plain objects. Use custom middleware for async actions."
even though i use thunk as a middleWare.
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { allReducers } from './reducers';
import thunk from 'redux-thunk';
import { getAllCourses } from './../../utils/courseServices';
export const store = createStore(allReducers, composeWithDevTools(
applyMiddleware(thunk),
// other store enhancers if any
));
//initiliaze
store.dispatch(getAllCourses())
//subscribe
store.subscribe(()=>console.log(store.getState()))
还有我的行动:
import { getAllCourses } from "../../utils/courseServices"
export const courseAction = () =>{
return async dispatch =>{
//fetching data from server
const {data} = await getAllCourses()
await dispatch({type:"INIT" , payload: data.courses})
}
}
您正在向 getAllCourses
派遣,而不是 courseAction
。这可能是你的问题。
此外,请注意,在新代码中,您应该使用 @reduxjs/toolkit
的 configureStore
,而不是 createStore
。现代 Redux 不使用 switch..case reducers、ACTION_TYPES、不可变的 reducer 更新逻辑、hand-written action creators 或 connect/mapStateToProps。 (这不是什么新鲜事,而是自 2019 年以来的推荐)。
您可能正在学习过时的教程 - 请遵循 the official Redux tutorial
我收到这个错误:
"Actions must be plain objects. Use custom middleware for async actions." even though i use thunk as a middleWare.
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { allReducers } from './reducers';
import thunk from 'redux-thunk';
import { getAllCourses } from './../../utils/courseServices';
export const store = createStore(allReducers, composeWithDevTools(
applyMiddleware(thunk),
// other store enhancers if any
));
//initiliaze
store.dispatch(getAllCourses())
//subscribe
store.subscribe(()=>console.log(store.getState()))
还有我的行动:
import { getAllCourses } from "../../utils/courseServices"
export const courseAction = () =>{
return async dispatch =>{
//fetching data from server
const {data} = await getAllCourses()
await dispatch({type:"INIT" , payload: data.courses})
}
}
您正在向 getAllCourses
派遣,而不是 courseAction
。这可能是你的问题。
此外,请注意,在新代码中,您应该使用 @reduxjs/toolkit
的 configureStore
,而不是 createStore
。现代 Redux 不使用 switch..case reducers、ACTION_TYPES、不可变的 reducer 更新逻辑、hand-written action creators 或 connect/mapStateToProps。 (这不是什么新鲜事,而是自 2019 年以来的推荐)。
您可能正在学习过时的教程 - 请遵循 the official Redux tutorial