You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Axios的Uncaught (in promise)错误及401授权问题

React调用GitHub API出现401未授权错误的排查与解决

问题描述

React项目调用GitHub API时,控制台抛出Axios的Uncaught (in promise)错误,状态码401,UserSearch.jsx的handleSubmit函数末尾出现错误标记。

相关代码

UserSearch.jsx

import { useState, useContext } from "react";
import GithubContext from "../../context/github/GithubContext";
import AlertContext from "../../context/alert/AlertContext";
import { searchUsers } from "../../context/github/GithubActions";

function UserSearch() {
  const [text, setText] = useState('')

  const { users, dispatch } = useContext(GithubContext)
  const { setAlert } = useContext(AlertContext)

  const handleChange = (e) => setText(e.target.value)

  const handleSubmit = async (e) => {
    e.preventDefault()

    if (text === '') {
      setAlert('Please enter something', 'error')
    } else {
      dispatch({ type: 'SET_LOADING' })
      const users = await searchUsers(text)
      dispatch({ type: 'GET_USERS', payload: users })

      setText('')
    }
  }

  return (
    <div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'>
      <div>
        <form onSubmit={handleSubmit}>
          <div className='form-control'>
            <div className='relative'>
              <input
                type='text'
                className='w-full pr-40 bg-gray-200 input input-lg text-black'
                placeholder='Search'
                value={text}
                onChange={handleChange}
              />
              <button
                type='submit'
                className='absolute top-0 right-0 rounded-l-none w-36 btn btn-lg'
              >
                Go
              </button>
            </div>
          </div>
        </form>
      </div>
      {users.length > 0 && (
        <div>
          <button
            onClick={() => dispatch({ type: "CLEAR_USERS" })}
            className='btn btn-ghost btn-lg'
          >
            Clear
          </button>
        </div>
      )}
    </div>
  );
}

export default UserSearch;

GithubActions.js

import axios from 'axios'
const GITHUB_URL = process.env.REACT_APP_GITHUB_URL
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN

const github = axios.create({
  baseURL: GITHUB_URL,
  headers: { Authorization: `token ${GITHUB_TOKEN}` },
})

// Get search results
export const searchUsers = async (text) => {
  const params = new URLSearchParams({
    q: text,
  })

  const response = await github.get(`/search/users?${params}`)
  return response.data.items
}

// Get user and repos
export const getUserAndRepos = async (login) => {
  const [user, repos] = await Promise.all([
    github.get(`/users/${login}`),
    github.get(`/users/${login}/repos`),
  ])

  return { user: user.data, repos: repos.data }
}

控制台错误信息

GET https://api.github.com/search/users?q=brad 401
dispatchXhrRequest @ xhr.js:220
xhrAdapter @ xhr.js:16
dispatchRequest @ dispatchRequest.js:58
request @ Axios.js:109
Axios.<computed> @ Axios.js:131
wrap @ bind.js:9
searchUsers @ GithubActions.js:16
handleSubmit @ UserSearch.jsx:21
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430

UserSearch.jsx:26 // 错误标记显示在函数末尾的大括号处
 
Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
handleSubmit @ UserSearch.jsx:26
await in handleSubmit (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430

错误原因

  • GitHub API授权失败:401状态码表示请求未被授权,核心原因是请求中携带的GitHub Token无效,或者Token未正确配置。
  • 环境变量问题:GITHUB_TOKEN环境变量可能未正确设置,导致Axios请求的Authorization头为空或无效值。
  • 未处理Promise错误:handleSubmit是async函数,调用searchUsers时未用try/catch捕获错误,导致Promise拒绝时抛出未捕获异常,错误标记显示在函数末尾是因为async函数的Promise链未处理错误。

解决步骤

1. 确认GitHub Token有效性与配置

  • 登录GitHub账号,进入Settings > Developer settings > Personal access tokens,生成新的token(勾选public_repo权限即可满足用户搜索需求)。
  • 在React项目根目录创建.env文件,添加正确的环境变量:
    REACT_APP_GITHUB_URL=https://api.github.com
    REACT_APP_GITHUB_TOKEN=你的GitHub个人访问令牌
    
  • 重启React开发服务器,确保环境变量被正确加载(React仅识别前缀为REACT_APP_的环境变量)。

2. 修复Promise错误捕获

修改UserSearch.jsx中的handleSubmit函数,添加try/catch捕获请求错误:

const handleSubmit = async (e) => {
  e.preventDefault()

  if (text === '') {
    setAlert('Please enter something', 'error')
  } else {
    try {
      dispatch({ type: 'SET_LOADING' })
      const users = await searchUsers(text)
      dispatch({ type: 'GET_USERS', payload: users })

      setText('')
    } catch (err) {
      // 根据错误类型提示用户
      if (err.response?.status === 401) {
        setAlert('GitHub API授权失败,请检查Token配置', 'error')
      } else {
        setAlert('搜索用户失败,请稍后重试', 'error')
      }
      // 重置加载状态
      dispatch({ type: 'SET_LOADING', payload: false })
    }
  }
}

3. 验证Axios请求头

可以在GithubActions.js中添加日志,确认Token是否正确传入(开发环境临时调试用,上线前删除):

console.log('GitHub Token:', GITHUB_TOKEN)
const github = axios.create({
  baseURL: GITHUB_URL,
  headers: { Authorization: `token ${GITHUB_TOKEN}` },
})

内容的提问来源于stack exchange,提问作者Avinash Vagh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:03:32