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

react-native-user-inactivity连续触发silentRenew 未按30秒间隔执行如何解决

问题根因

  • react-native-user-inactivity的onAction回调会在两种场景触发:一是用户闲置达到timeForInactivity时长时返回isActive=false,二是检测到用户新操作重置计时器时返回isActive=true。你当前未对isActive值做判断,两种场景都会执行silentRenew,导致触发频率远超预期。
  • 未给silentRenew加执行冷却限制,短时间内多次触发回调时会重复调用续期接口。

解决方案

步骤1:新增冷却状态控制

在UserActivityMonitor组件内新增冷却标识,保证silentRenew至少间隔30秒才能执行一次。

步骤2:补充isActive判断逻辑

根据你的业务需求确定触发时机:如果是用户闲置30秒时才续期,就判断isActive=false时执行;如果是用户活跃期间定时续期,就搭配冷却控制执行。

修改后的组件代码参考:

import UserInactivity from 'react-native-user-inactivity';
import BackgroundTimer from 'react-native-user-inactivity/lib/BackgroundTimer';
import { useRef } from 'react';

const UserActivityMonitor = (props) => {
    const { children } = props;
    const isRenewCooling = useRef(false);
    ...
    const handleIsActive = async (isActive) => {
        // 若仅需要用户闲置30秒时才续期,可额外加判断:if (!isActive) { 后续逻辑 }
        if (isRenewCooling.current) return;
        isRenewCooling.current = true;
        // 30秒后解除冷却
        setTimeout(() => {
            isRenewCooling.current = false;
        }, 30000);
        
        try {
            const success = await silentRenew();
            console.log(success)
            if (success === true) {
                setValidToken(success);
            }
        } catch (e) {
            logger.error(
                'Error occured while monitoring user activity',
                e,
            );
        }
    };

    return (
        <>
            <UserInactivity
                timeoutHandler={BackgroundTimer}
                timeForInactivity={30000}
                onAction={handleIsActive}
            >
                {children}
            </UserInactivity>
        </>
    );
};
export { UserActivityMonitor };

如果需要全局控制避免其他位置也触发重复请求,可以直接把冷却逻辑加在silentRenew函数内:

let isGlobalRenewCooling = false;
const silentRenew = async () => {
    if (isGlobalRenewCooling) return false;
    isGlobalRenewCooling = true;
    setTimeout(() => {
        isGlobalRenewCooling = false;
    }, 30000);
    try {
        const authdata = await getItem(AUTH_DATA);
        if (authdata) {
            const {
                refreshToken,
            } = JSON.parse(authdata);
            if (refreshToken) {
                await refreshAuthToken(refreshToken);
                return true;
            }
            return false;
        }
        return false;
    } catch (e) {
        logger.error('Error occurred while slient renew', e);
        return false;
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 20:06:01