使用createAsyncThunk.withTypes时出现初始化前访问错误求助
解决循环导入导致的
createAppAsyncThunk初始化错误 问题根源
你的store.ts导入了各个slice的reducer(比如代码里的home,还有实际用到的reservationPlaces),而slice文件又从store.ts导入createAppAsyncThunk,形成了循环依赖:
- store.ts → slice.ts(导入reducer)
- slice.ts → store.ts(导入createAppAsyncThunk)
这导致初始化时,createAppAsyncThunk还未完成定义,slice就尝试访问它,触发Cannot access 'createAppAsyncThunk' before initialization错误。
解决步骤
1. 抽离createAppAsyncThunk到独立文件
新建一个独立文件(比如src/app/typedThunk.ts),把类型定义和createAppAsyncThunk的创建逻辑移到这里:
import { createAsyncThunk } from '@reduxjs/toolkit' import type { RootState, AppDispatch } from './store' export type ThunkApiConfig = { state: RootState dispatch: AppDispatch } export const createAppAsyncThunk = createAsyncThunk.withTypes<ThunkApiConfig>()
2. 调整store.ts的代码
在store.ts中导出RootState和AppDispatch类型,并确保reducer配置完整:
import { configureStore } from '@reduxjs/toolkit' // 导入你的slice reducer import home from '../features/home/slice' import reservationPlaces from '../pages/ReservationPlaces/slice' export const store = configureStore({ reducer: { home, reservationPlaces } }) // 导出类型供typedThunk.ts使用 export type RootState = ReturnType<typeof store.getState> export type AppDispatch = typeof store.dispatch
3. 修改slice文件的导入路径
在slice文件中,从新建的typedThunk.ts导入createAppAsyncThunk,而非store.ts:
import { createAppAsyncThunk } from '../../app/typedThunk' import { createSlice } from '@reduxjs/toolkit' import api from './api' const name = 'reservationPlaces' interface State { selectedDate: string currentUserReservation: any // 替换为实际的类型定义 } const initialState = { selectedDate: '', currentUserReservation: null } as State export const getCurrentUserPlace = createAppAsyncThunk( `${name}/getCurrentUserPlace`, (arg, thunkAPI) => { const sendDay = thunkAPI.getState().reservationPlaces.selectedDate return api.getCurrentUserPlace(arg, sendDay) }, ) const slice = createSlice({ name, initialState, reducers: { }, extraReducers: builder => { builder.addCase(getCurrentUserPlace.fulfilled, (state, action) => { state.currentUserReservation = action.payload }) }, }) export default slice.reducer
原理说明
通过将createAppAsyncThunk的定义移到独立文件,打破了store与slice之间的循环依赖链:
- store.ts → slice.ts(仅导入reducer)
- slice.ts → typedThunk.ts(导入createAppAsyncThunk)
- typedThunk.ts → store.ts(仅导入静态类型,不会触发运行时初始化顺序问题)
静态类型导入不会影响运行时的变量初始化顺序,因此不会再出现“初始化前访问”的错误。
内容的提问来源于stack exchange,提问作者rozalinaag
相关产品推荐
相关产品推荐

