redux工具包:createSyncthunk- recublwithValue -typeError:无法破坏属性; ' ref2'由于不确定。”

发布于 2025-02-13 05:47:21 字数 2765 浏览 1 评论 0 原文

我一直在尝试使用Redux Toolkit进行Auth Refresh代币呼叫,但是在安装所有修复程序后,它仍然可以读取错误消息。

设置Axios实例:

export const axiosInstance = axios.create({
  baseURL: REACT_APP_API_URL,
});

进行API调用:

export const refreshAccessAndRefreshTokens = async () => {
  const response = await axiosInstance({
    method: 'post',
    url: '/refresh-tokens',
    withCredentials: true,
  });
  return response;
};

thunk函数:

// GET ACCESS TOKEN USING REFRESH TOKEN
export const refreshTokens = createAsyncThunk(
  'auth/refreshTokens',
  async ({ rejectWithValue }) => {
    try {
      const response = await refreshAccessAndRefreshTokens();
      return response.data;
    } catch (error) {
      console.log('error', error);
      console.log('data', error.response.data);
      console.log('message', error.response.data.message);
      return rejectWithValue(error.response.data.message);
    }
  }
);

auth slice中的额外还原器:

extraReducers: (builder) => {
    builder
      .addCase(refreshTokens.pending, (state) => {
        state.loading = true;
      })
      .addCase(refreshTokens.fulfilled, (state, action) => {
        state.loading = false;
        state.isAuthenticated = true;
        state.user = action.payload.user;
        state.roles = action.payload.roles;
      })
      .addCase(refreshTokens.rejected, (state, action) => {
        state.loading = false;
        state.success = false;
        state.message = action.payload;
        state.isAuthenticated = false;
        state.user = null;
        state.roles = [];
      })
  },

我能够要查看浏览器控制台中的错误,但是recuplwithMessage不起作用:

控制台输出:

redux输出:

在登录页面上通过使用效率将用户重定向到他来自的位置,以防万一他已经登录了。

useEffect(() => {
    dispatch(refreshTokens());
    dispatch(reset());
  }, [dispatch]);

  useEffect(() => {
    if (isAuthenticated) {
      if (roles.find((role) => role === process.env.REACT_APP_ROLE)) {
        navigate(from, { replace: true });
      } else {
        dispatch(
          errorFn({
            success: false,
            message: 'You are not authorized to access this page!',
          })
        );
      }
    }
  }, [dispatch, from, isAuthenticated, navigate, roles]);

I've been trying to make auth refresh token calls using Redux toolkit but after installing all fixes, it still is now able to read error message.

Setting up axios instance:

export const axiosInstance = axios.create({
  baseURL: REACT_APP_API_URL,
});

Making API call:

export const refreshAccessAndRefreshTokens = async () => {
  const response = await axiosInstance({
    method: 'post',
    url: '/refresh-tokens',
    withCredentials: true,
  });
  return response;
};

Thunk function:

// GET ACCESS TOKEN USING REFRESH TOKEN
export const refreshTokens = createAsyncThunk(
  'auth/refreshTokens',
  async ({ rejectWithValue }) => {
    try {
      const response = await refreshAccessAndRefreshTokens();
      return response.data;
    } catch (error) {
      console.log('error', error);
      console.log('data', error.response.data);
      console.log('message', error.response.data.message);
      return rejectWithValue(error.response.data.message);
    }
  }
);

Extra reducers in auth slice:

extraReducers: (builder) => {
    builder
      .addCase(refreshTokens.pending, (state) => {
        state.loading = true;
      })
      .addCase(refreshTokens.fulfilled, (state, action) => {
        state.loading = false;
        state.isAuthenticated = true;
        state.user = action.payload.user;
        state.roles = action.payload.roles;
      })
      .addCase(refreshTokens.rejected, (state, action) => {
        state.loading = false;
        state.success = false;
        state.message = action.payload;
        state.isAuthenticated = false;
        state.user = null;
        state.roles = [];
      })
  },

I'm able to see the errors in browser console, but rejectWithMessage is not working:

Console output:

console output

Redux output:

redux output

Refresh Tokens is being called on login page through useEffect to redirect the user to where he came from in case he is already logged in.

useEffect(() => {
    dispatch(refreshTokens());
    dispatch(reset());
  }, [dispatch]);

  useEffect(() => {
    if (isAuthenticated) {
      if (roles.find((role) => role === process.env.REACT_APP_ROLE)) {
        navigate(from, { replace: true });
      } else {
        dispatch(
          errorFn({
            success: false,
            message: 'You are not authorized to access this page!',
          })
        );
      }
    }
  }, [dispatch, from, isAuthenticated, navigate, roles]);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

动次打次papapa 2025-02-20 05:47:21

传递给回调函数的第一个参数您给出 createSyncthunk 是您调用操作时通过的参数。
在这里查看此处以获取更多信息。第二个参数是 thunkapi thunkapi 包含 recondwithValue 。尝试将虚拟参数作为回调的第一个参数 -

// GET ACCESS TOKEN USING REFRESH TOKEN
export const refreshTokens = createAsyncThunk(
  'auth/refreshTokens',
  async (_, { rejectWithValue }) => {
    try {
      const response = await refreshAccessAndRefreshTokens();
      return response.data;
    } catch (error) {
      console.log('error', error);
      console.log('data', error.response.data);
      console.log('message', error.response.data.message);
      return rejectWithValue(error.response.data.message);
    }
  }
);

The first argument that is passed to the callback function you give to createAsyncThunk is the argument that you pass when you call the action.
take a look here for more information. The second argument is the thunkAPI which contains the rejectWithValue. Try putting a dummy parameter as the first parameter to the callback like this -

// GET ACCESS TOKEN USING REFRESH TOKEN
export const refreshTokens = createAsyncThunk(
  'auth/refreshTokens',
  async (_, { rejectWithValue }) => {
    try {
      const response = await refreshAccessAndRefreshTokens();
      return response.data;
    } catch (error) {
      console.log('error', error);
      console.log('data', error.response.data);
      console.log('message', error.response.data.message);
      return rejectWithValue(error.response.data.message);
    }
  }
);
世界和平 2025-02-20 05:47:21
export const canLogin = createAsyncThunk("AUTH/login", 
async (loginData ,{ rejectWithValue })=> {
    try{
        const response=await axios.post(AuthConfig.API_URL + AuthConfig.LOGIN_URI, loginData)
        return response
    }
    catch(error){
        if (!error.response || !error.message) 
            throw error
        return rejectWithValue(getErrorMessage(error))
    }    
  }
);

export function getErrorMessage(error) {
    return (
      error?.response?.data?.message ||
      error?.response?.data.error ||
      error?.response?.data ||
      error?.message ||
      error.toString()
    );
}
export const canLogin = createAsyncThunk("AUTH/login", 
async (loginData ,{ rejectWithValue })=> {
    try{
        const response=await axios.post(AuthConfig.API_URL + AuthConfig.LOGIN_URI, loginData)
        return response
    }
    catch(error){
        if (!error.response || !error.message) 
            throw error
        return rejectWithValue(getErrorMessage(error))
    }    
  }
);

export function getErrorMessage(error) {
    return (
      error?.response?.data?.message ||
      error?.response?.data.error ||
      error?.response?.data ||
      error?.message ||
      error.toString()
    );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文