在Redux RTK slice中添加asyncThunk时,为什么会出现“Cannot access 'Slice' before initialization”错误?

nr9pn0ug  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(275)

我遇到了一个错误,我很难分离出源。
Web应用程序内置于ReactJs / Vite和RTK中。
我创建了一个简单的RTK切片。
当我向我的切片添加asyncThunk时,应用程序崩溃,我得到以下错误:
Uncaught ReferenceError: Cannot access 'tagsSlice' before initialization
我都做过一千次了。
添加一个常规的行动减少是好的。
我不明白为什么。
与我之前的项目相比,唯一的新东西是Vite。
错误是从store.ts抛出的,下面是文件:

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
import appTimeSpanSlice from './slices/appTimeSpanSlice';
import authenticationSlice from './slices/authenticationSlice';
import uiBehaviorHandlerSlice from './slices/uiBehaviorHandlerSlice';
import intervalMiddleware from './middlewares/intervalMiddleware';
import pollingMiddleware from './middlewares/pollingMiddleware';
import tagsSlice from './slices/tagsSlice'

export const store = configureStore({
  reducer: {
    tag: tagsSlice, // <--- ERROR IS THROWN HERE
    appTime: appTimeSpanSlice,
    authentication: authenticationSlice,
    ui: uiBehaviorHandlerSlice,
  },
  middleware: [thunk, intervalMiddleware, pollingMiddleware],
});

export type RootState = ReturnType<typeof store.getState>
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

这是我的切片:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { tagApi } from 'services/tag/tagApi'


 export const createTag = createAsyncThunk(
   'tags/createTags',
   async (body, thunkAPI) => {
     const response = await tagApi.createTag(body);
     return response.data;
   }
 );

enum Status {
  IDLE = 'idle',
  PENDING = "pending",
  FULFILLED = "fulfilled",
  REJECTED = "rejected"
}

interface TagsState {
  tags: [];
  fetchTagsStatus: Status;
  createTagStatus: Status;
}

const initialState = {
  tags: [],
  fetchTagsStatus: Status.IDLE,
  createTagStatus: Status.IDLE
} as TagsState

const tagsSlice = createSlice({
  name: 'tags',
  initialState,
  reducers: {
   testAction: () => { console.log("Hello")}
  },
  extraReducers: (builder) => {
    builder
     .addCase(createTag.pending, state => {
       state.createTagStatus = Status.PENDING;
     })
     .addCase(createTag.fulfilled, (state, { payload }) => {
       state.createTagStatus = Status.FULFILLED;
     })
     .addCase(createTag.rejected, (state, { error }) => {
       state.createTagStatus = Status.REJECTED;
     })
   },
})

const { actions, reducer } = tagsSlice;
export const { testAction } = actions;
export default reducer;

综上所述,为了重现该问题,应满足2个条件:

  • 切片应包含asyncThunk
  • 组件应该导入asyncThunk
    故障排除步骤:
  • 如果切片中有NOasyncThunk,但导入了testAction动作:无错误
  • 如果切片中有asyncThunk,但组件没有导入文件中的任何内容:没有错误
  • 如果slice中有asyncThunk并且,则导入testAction动作:错误

什么可能导致这种行为?

ckocjqey

ckocjqey1#

问题是我试图访问React组件之外的商店。
这是我的想法:

import api from 'services/api';
import { selectStart, selectEnd } from 'store/slices/appTimeSpanSlice';
import { store } from 'store/store';

export const tagApi = {
  fetchAllTags: async () => {
    const start = selectStart(store.getState()); <<< not allowed
    const end = selectEnd(store.getState()); <<< not allowed
    const url = `/api/tags?start=${start}&end=${end}`;
    return await api.get(url);
  },
  createTag: async (body: any) => {
    const url = `/api/tags`;
    return await api.post(url, body);
  }
};

下面是我如何修复它的:

import api from 'services/api';
import { selectStart, selectEnd } from 'store/slices/appTimeSpanSlice';

export const tagApi = {
  fetchAllTags: async (start, end) => {
    const url = `/api/tags?start=${start}&end=${end}`;
    return await api.get(url);
  },
  createTag: async (body: any) => {
    const url = `/api/tags`;
    return await api.post(url, body);
  }
};

相关问题