带有 Typescript 的 Redux 工具包。无法分派由 createAsyncThunk 创建的操作

Redux-Toolkit with Typescript. Cannot dispatch action created by createAsyncThunk

我正在使用 ReactRedux-Toolkit 实现登录功能。但是,当我尝试发送由 createAsyncThunk 函数创建的操作时,出现错误:

Argument of type 'AsyncThunkAction<User, UserCredentials, {}>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type 'AsyncThunkAction<User, UserCredentials, {}>' but required in type 'AnyAction'.ts(2345)

我在 Google 中搜索了可能的解决方案,但找不到适合我的情况。 这是我根据官方 Redux-Toolkit 文档完成的实现。

用户-slice.ts:

    export interface User {
      UserId: string;
      Name: string;
      Token: string;
    }
    
    export interface UserCredentials {
      username: string;
      password: string;
    }
    
    interface AuthState {
      currentUser: User | null;
      loading: boolean;
      error: string | null;
    }
    
    const initialState: AuthState = {
      currentUser: null,
      loading: false,
      error: null
    };
    
    export const userLogin = createAsyncThunk<User, UserCredentials>(
      'users/login',
      async (credentials: UserCredentials) => {
        const response = await fetch(`${apiRest()}login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(credentials)
        });
        console.log(await response.json());
        return (await response.json()) as User;
      }
    );
    
    export const userSlice = createSlice({
      name: 'users',
      initialState,
      reducers: { },
      extraReducers: (builder) => {
        builder
          .addCase(userLogin.pending, state => {
            state.currentUser = null;
            state.loading = true;
            state.error = null;
          })
          .addCase(userLogin.fulfilled, (state, action) => {
            state.loading = false;
            state.currentUser = action.payload;
            state.error = null;
          })
          .addCase(userLogin.rejected, (state, action) => {
            state.currentUser = null;
            state.loading = false;
            if(action.payload) {
              state.error = action.payload as string;
            } else {
              state.error = 'Failed user to login';
            }
          });
      }
    });
    
    export default userSlice.reducer;

store.ts:

export const store = configureStore({
  reducer: {
    user: userReducer,
  }
});

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

hooks.ts:

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

登录-page.tsx:

export const LoginPage: React.FC = () => {
  const dispatch = useAppDispatch();

  const onLoginSubmit =
  useCallback(
    (login, password) =>   
      // Getting the following error here:   
      // Argument of type 'AsyncThunkAction<User, UserCredentials, {}>' is not assignable to parameter of type 'AnyAction'.
      // Property 'type' is missing in type 'AsyncThunkAction<User, UserCredentials, {}>' but required in type 'AnyAction'.
      dispatch(userLogin({username: login, password})),
    [dispatch]
  );

  const loginErrorText = useSelector(loginError);

  return (
    <div>
      <LoginForm
        onSubmit={onLoginSubmit}
        loginError={loginErrorText}
      />
    </div>
  );
};

在此先感谢您的帮助!

由于您的设置似乎是正确的,我假设您遇到了一个罕见的错误,即 redux 4.0.5 和 redux 4.1.0 在您的 node_modules 中并排安装。我会检查一下。

为了它的价值,我走上了 redux 版本、yarn --flat、包升级等这条道路

我的 useAppDispatch 输入正确,但我不确定它可能是什么。

虽然上面的评论可能已经解决了这个问题,但我的问题是由以下愚蠢的错误解决的:

导入动作必须放在大括号中,如下所示:

import { action } from '../path/to/slice';

我没有正确导入操作,而是它选择了我的 reducer 对象。希望这对遇到同样问题的人有所帮助!