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

React函数式组件表单提交触发栈溢出错误求排查

问题分析与解决方案

嘿,这个错误的原因特别明显——你不小心写出了无限递归!

看你Create.js里的这段代码:

const postUsers = async () => {
  let res = await postUsers(mobileCountryCode)
  console.log("postUsers.res:")
  console.log(res)
}

你在自己定义的postUsers函数里,又调用了同名的postUsers,但这里调用的根本不是你封装好的axios请求函数,而是当前这个组件里的函数本身!每调用一次就会触发新的调用,调用栈不断堆叠,直到超出浏览器的最大栈容量,就抛出了Maximum call stack size exceeded错误。

解决办法

有两种简单的方式可以解决这个命名冲突问题:

1. 给封装的API请求函数重命名

在你的postUsers.js里,把导出的函数改个名字,比如加上Api后缀来区分:

// postUsers.js
import axios from 'axios'

export const postUsersApi = async (mobileCountryCode) => {
  // 原来的axios请求逻辑,比如:
  return await axios.post('/api/users', { mobileCountryCode })
}

然后在Create.js里调用这个重命名后的函数:

// Create.js
import { postUsersApi } from './postUsers.js'

const postUsers = async () => {
  let res = await postUsersApi(mobileCountryCode)
  console.log("postUsers.res:")
  console.log(res)
}

2. 导入时使用别名

如果不想修改封装函数的名字,可以在导入的时候给它起一个别名:

// Create.js
import { postUsers as postUsersApi } from './postUsers.js'

const postUsers = async () => {
  let res = await postUsersApi(mobileCountryCode)
  console.log("postUsers.res:")
  console.log(res)
}

小建议

以后写代码的时候,尽量给API请求函数和业务逻辑函数起不同的命名,比如给API函数加Api、Request这类后缀,能有效避免这种低级的命名冲突问题哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:47:46