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

VueJS定时GET请求重复数据问题:如何避免重复与卡顿?

Solution to Prevent Duplicate Data & Fix Update Errors

Key Issues in Your Code

  • Duplicate Entries: You’re appending new data to existing symbols/price arrays instead of replacing them, leading to repeated symbols and "Duplicate keys" errors.
  • Useless await on forEach: forEach doesn’t return a promise, so adding await here has no effect.
  • Overly Frequent Requests: 500ms intervals trigger excessive API calls, causing performance lag and potential rate limiting.

Step-by-Step Fixes

  1. Replace Data Entirely Instead of Appending
    Generate fresh arrays from each API response and overwrite the old data to eliminate duplicates:

    methods: {
      async fetchApi() {
        try {
          const response = await fetch('https://api2.binance.com/api/v3/ticker/24hr');
          if (!response.ok) throw new Error(`HTTP status: ${response.status}`);
          const data = await response.json();
          
          // Create new arrays with the latest ticker data
          const newSymbols = data.map(item => item.symbol);
          const newPrices = data.map(item => +item.lastPrice);
          
          // Replace existing data to avoid duplicates
          this.chartData.symbols = newSymbols;
          this.chartData.price = newPrices;
        } catch (error) {
          console.error('Failed to fetch data:', error);
        }
      }
    }
    
  2. Adjust Interval Timing

    • For testing: Use a longer interval (e.g., 10 seconds = 10000 ms) to avoid overwhelming your app and the API.
    • For production: Set to 20 minutes (20 * 60 * 1000 = 1200000 ms):
    async created() {
      this.loaded = false;
      // Test interval: 10s, production: 1200000ms
      this.timer = setInterval(this.fetchApi, 10000);
      this.loaded = true;
    }
    
  3. Clean Up Interval to Avoid Memory Leaks
    Clear the interval when the component is unmounted to prevent unnecessary background requests:

    beforeUnmount() {
      clearInterval(this.timer);
    }
    

Additional Notes

  • Ensure your template uses unique keys (e.g., :key="symbol" in v-for)—this error will disappear now that symbols contains no duplicates.
  • The Binance API returns the full list of tickers on each request, so replacing the entire array is the most efficient way to keep data up-to-date.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:05:31