发送到客户端后无法设置 headers axios next.js

Cannot set headers after they are sent to the client axios next.js

Same question on GitHub - https://github.com/axios/axios/issues/2743

我的 Next.js 项目中有 Axios,当 return 和 Promise.reject.

时,有时我会因为拦截器而出错

错误:发送给客户端后无法设置headers。

我在getInitialProps请求时遇到了这个问题。当我重新启动 PC 并再次打开页面时,这种情况很少发生。

Axios 实例:

const instance = axios.create({
  baseURL: 'https://my-api.com',
  withCredentials: true,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
})

instance.interceptors.response.use(undefined, error => {
  if (error.response.status === 401) {
    console.log("UNAUTHORIZED")
  }
  return Promise.reject(error) // <-- this cause the problem
})

Next.js 页面示例:

const Index = ({myData}) => {
  return data.map(...)
}

Index.getInitialProps = async ({req}) => {
  let myData

  try {
    const res = await API.get('/my-request', {
      headers: req ? { cookie: req.headers.cookie } : undefined, //setting cookie
    })
    myData = res.data
  } catch (e) {}

  return {myData}
}

Axios 0.19.0升级到0.19.2后问题消失了¯_(ツ)_/¯