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

如何处理响应式异步Fetch输入字段错误及绑定失效问题?

问题分析与解决方案

问题根源

  1. 输入类型不匹配:输入框绑定的Id默认是字符串类型,空字符串、非数字字符串会触发错误逻辑分支——比如空字符串会被>=0判断为true,调用getNewThing(0),但接口不接受0参数。
  2. 无效返回值未处理:当请求失败或接口返回null时,store被设置为无property字段的对象或null,模板直接访问{$thingStore.property}会抛出TypeError,导致组件更新中断,后续输入绑定失效。
  3. 接口参数校验缺失:getNewThing未提前拦截无效参数,导致无效请求触发接口错误。

修复步骤

1. 修正输入处理与请求逻辑

先将输入字符串转为有效数字,校验合法范围后再发起请求,同时捕获Promise异常:

<script>
  let inputId = '';
  export let thingStore = writable({ property: '请输入1-9675之间的数字' });

  $: {
    const parsedId = parseInt(inputId, 10);
    // 校验是否为有效数字且在合法范围内
    const validId = !isNaN(parsedId) && parsedId >= 1 && parsedId <= 9675;

    if (validId) {
      getNewThing(parsedId)
        .then(newThing => thingStore.set(newThing ?? { property: '未找到对应数据' }))
        .catch(() => thingStore.set({ property: '请求失败,请重试' }));
    } else {
      thingStore.set({ property: '请输入1-9675之间的有效数字' });
    }
  }
</script>

<input type="text" bind:value={inputId}>
<div>{$thingStore.property}</div>

2. 优化接口请求函数

提前校验参数有效性,确保无论成功/失败都返回带property字段的对象:

import { client } from "../lib/graphql-client";
import { gql } from "graphql-request";

const maxId = 9675;

export const getNewThing = async (Id) => {
  // 提前拦截无效参数
  if (isNaN(Id) || Id < 1 || Id > maxId) {
    return { property: 'ID必须是1-9675之间的数字' };
  }

  try {
    const query = gql`
      query newThing { 
        property: "${Id}" 
      }        
    `;
    const newThing = await client.request(query);
    // 处理接口返回null的情况
    return newThing ?? { property: '未找到对应数据' };
  } catch (error) {
    return { property: `请求出错:${error.message}` };
  }
};

3. 模板添加防御性访问(可选)

即使store数据异常,也不会导致组件崩溃:

<div>{$thingStore?.property ?? '无数据'}</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:18:18