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

React TypeScript中Axios API请求processUser执行不稳定问题

接口请求不稳定:processUser方法并非每次执行

我通过NSwag Studio生成了TypeScript客户端,其中添加用户的接口代码如下:

user(authorization?: any | undefined, body?: AddUserDto | undefined , cancelToken?: CancelToken | undefined): Promise<NewUserDto> {
        let url_ = this.baseUrl + "/add_user";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(body);

        let options_ = <AxiosRequestConfig>{
            data: content_,
            method: "POST",
            url: url_,
            headers: {
                "Authorization": authorization !== undefined && authorization !== null ? "" + authorization : "",
                "Content-Type": "application/json-patch+json",
                "Accept": "text/plain"
            },
            cancelToken
        };

        return this.instance.request(options_).catch((_error: any) => {
            if (isAxiosError(_error) && _error.response) {
                return _error.response;
            } else {
                throw _error;
            }
        }).then((_response: AxiosResponse) => {
            return this.processUser(_response);
        });
    }

在React项目中调用该接口时,return this.processUser(_response);这一行并非每次都会执行。我曾认为这和组件重渲染有关,尝试用Context解决但没有效果。以下是相关的调用链代码:

ApiClientWrapper中的addNewUser方法

public addNewUser(id: number, name: string, surname: string, date: Date): Promise<NewUserDto>{
        let dto = new AddUserDto({ id: id, name: name, surname: surname, date: date });
        return this._add.user(this.getToken(), dto)
            .then(response => this.updateUser().then(() => response))
            .catch(error => {
                let apiError  = error as ApiException;

                if (apiError === null || apiError.status !== Unauthorized){
                    console.error(error);
                    this._tokenService.reset();
                    return new NewUserDto();
                }

                return this.updateToken()
                    .then(() => this._add.user(this.getToken(), dto))
                    .catch(error => {
                        console.error(error);
                        this._tokenService.reset();
                        return new NewUserDto();
                    });
            });
    }

表单提交处理函数handleCreateNewUser

const handleCreateNewUser = async (identifier: number, client: ApiClientWrapper, form: HTMLFormElement, date: Date): Promise<string> => {
    let name:string = "";
    let surname: string = "";
    for (let i = 0; i < form.length; i++){
        if (form[i].localName !== "input"){
            continue;
        }

        let element = (form[i] as HTMLInputElement);
        if (element.id === NAME_ID){
            name = element.value;
        }

        if (element.id === SURNAME_ID){
            surname = element.value;
        }
    };

    try {
        const response = await client.addNewUser(identifier, name, surname, date);
        return `Login: ${response.login}; Password: ${response.password}`;
    } catch (exception) {
        console.error(exception);
        return "";
    }
};

AddUser组件

const AddUser: FC = () => {
    const [date, setDate] = useState(new Date());
    const [submitting, setSubmitting] = useState(false);
    const client = new ApiClientWrapper(useAppDispatch());
    const identifier = useAppSelector(selectUserIdentifier);
    const setMessage = useContext(MessageContext);
    return(
        <Form 
            className='main-account-container'
            onSubmit={event => {
                setSubmitting(true);
                let form = event.target as HTMLFormElement;
                handleCreateNewUser(identifier, client, form, date)
                    .then(message => { 
                        setMessage(message);
                        setSubmitting(false);
                        })
                    .catch(error => console.error(error));
                    }
                }
            >
        </Form>);
}

AccountPage组件

const AccountPage: FC = () => {
    const initialValues: IChangePasswordForm = { password: "", newPassword: "", confirmPassword: "" };
    const initErrors: IChangePasswordForm = { password: "", newPassword: "", confirmPassword: "" };
    const [submitting, setSubmitting] = useState(false);
    const [passwordForm, setPasswordForm] = useState(initialValues);
    const [errors, setErrors] = useState(initErrors);
    const [message, setMessage] = useState("");
    useEffect(() => {
        if (message !== ""){
            navigator.clipboard.writeText(message);
        }
    }, [message]);

    const displayedName = useAppSelector(selectUserName);
    const admin = useAppSelector(selectUserIsAdmin);
    const client = new ApiClientWrapper(useAppDispatch());
    return(
        <WorkingArea>
            <div className='account-page-root'>
                <div className='account-header'>{admin ? "Менеджер" : "Продавец"} {displayedName}</div>
                {admin ? <MessageContext.Provider value={setMessage}><AddUser /></MessageContext.Provider> : <Container />}
                {admin ? <RemoveUser /> : <Container />}
            </div>
        </WorkingArea>);
}

我还尝试过以下方案,但都没有解决问题:

  • 用useRef存储响应结果
  • 为handleCreateNewUser添加useCallback
  • 将then链式调用替换为async/await

调试器仍然不是每次都会进入return this.processUser(_response);这一行,React也没有抛出任何错误,请求无法稳定完成。


内容的提问来源于stack exchange,提问作者Роман Кармацкий

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:45:04