如何解决 '属性 'type' is missing in type 'AsyncThunkAction' using Redux Toolkit (with TypeScript)?

How do I resolve 'Property 'type' is missing in type 'AsyncThunkAction' using Redux Toolkit (with TypeScript)?

我在下面的 thunk/slice 中使用 Redux Toolkit。我想我可以通过等待 thunk 承诺解决来在本地处理它们,而不是在状态中设置错误,using the example provided here.

我想我可以避免这样做,也许我应该通过在状态中设置一个 error 但我有点想了解我在这方面哪里出错了。

Argument of type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' is not assignable to parameter of type 'Action<unknown>'.
  Property 'type' is missing in type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' but required in type 'Action<unknown>'

resultAction传递给match时出现错误:

const onSubmit = async (data: LoginFormData) => {
  const resultAction =  await dispatch(performLocalLogin(data));
  if (performLocalLogin.fulfilled.match(resultAction)) {
    unwrapResult(resultAction)
  } else {
    // resultAction.payload is not available either
  }
};

轰动:

export const performLocalLogin = createAsyncThunk(
  'auth/performLocalLogin',
  async (
    data: LoginFormData,
    { dispatch, requestId, getState, rejectWithValue, signal, extra }
  ) => {
    try {
      const res = await api.auth.login(data);
      const { token, rememberMe } = res;
      dispatch(fetchUser(token, rememberMe));
      return res;
    } catch (err) {
      const error: AxiosError<ApiErrorResponse> = err;
      if (!error || !error.response) {
        throw err;
      }
      return rejectWithValue(error.response.data);
    }
  }
);

切片:

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: { /* ... */ },
  extraReducers: builder => {
    builder.addCase(performLocalLogin.pending, (state, action) => startLoading(state));
    builder.addCase(performLocalLogin.rejected, (state, action) => {
      //...
    });
    builder.addCase(performLocalLogin.fulfilled, (state, action) => {
      if (action.payload) {
        state.rememberMe = action.payload.rememberMe;
        state.token = action.payload.token;
      }
    });
  }
})

感谢您的帮助!

很确定您使用的是标准内置 Dispatch 类型,它对 thunk 一无所知。

根据 Redux 和 RTK 文档,您需要定义一个更具体的 AppDispatch 类型,该类型正确了解 thunk 并声明 dispatch 此处是该类型,例如:

    // store.ts
    export type AppDispatch = typeof store.dispatch;

    // MyComponent.ts
    const dispatch : AppDispatch = useDispatch();

    const onSubmit = async () => {
        // now dispatch should recognize what the thunk actually returns
    }

我必须将 middleware: [thunk as ThunkMiddleware] 添加到我的 configureStore() 以获得 createAsyncThunk() 的正确类型

如果 none 的其他答案有帮助,那么最终对我有用的一件事是:

  1. 删除 node_modules 文件夹。
  2. 删除yarn.lock/package-lock.json.
  3. 运行 yarn install/npm install.

如果您像我一样确保您的其余代码看起来完全正确,那么这应该会为您解决问题。