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

React中出现Uncaught TypeError: setName is not a function错误求解决

解决Uncaught TypeError: setName/setEmail/setPassword is not a function错误

错误核心原因

useState Hook的返回值是数组,不是对象。你用了对象解构const {name, setName} = useState(''),这种方式会从返回值里找名为name和setName的属性,但数组根本没有这些属性,导致setName等变量为undefined,调用时就会触发"不是函数"的错误。

修复步骤

  1. 修正useState解构方式
    把所有对象解构改成数组解构:

    const [isSignup, setIsSignup] = useState(false)
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    
  2. 修复JSX语法错误
    原代码的JSX存在未闭合标签(<div>、<section>、<form>都没有对应的结束标签),且export default Auth写在了组件的return语句内部,这会导致语法错误。需要补全所有闭合标签,并将导出语句移到组件外部。

完整修正后的代码

import React, {useState} from 'react'
import './Auth.css'
import icon from '../../assets/logo.svg'
import AboutAuth from './AboutAuth'

const Auth = () => {
    const [isSignup, setIsSignup] = useState(false)
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const handleSwitch = () => {
        setIsSignup(!isSignup)
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log({ name, email, password})
    }

    return (
        <div>
            <section className='auth-section'>
                {isSignup && <AboutAuth />}
                <div className='auth-container'>
                    {!isSignup && <img src={icon} width='50px' alt='stack overflow' className='login-logo' />}
                    <form onSubmit={handleSubmit}>
                        {isSignup && (
                            <label htmlFor='name'>
                                <h4>Display Name</h4>
                                <input type="text"  id='name' name='name' onChange={(e) => {setName(e.target.value)}} />
                            </label>
                        )}
                        <label htmlFor="email">
                            <h4> Email </h4>
                            <input type="email" name='email' id='email' onChange={(e) => {setEmail(e.target.value)}} />
                        </label>
                        <input type="password" name='password' id='password' onChange={(e) => {setPassword(e.target.value)}}/>
                    </form>
                </div>
            </section>
        </div>
    )
}

export default Auth

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:35:45