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

React订阅组件报错Unhandled Rejection (SyntaxError):Unexpected end of input求解

Fixing Your React Email Subscription Component Error

Hey Ricardo, let's break down why you're seeing that Unexpected end of input error and get your subscription feature working properly. Here's what's going wrong and how to fix it:

Key Issues in Your Current Code

  • mode: 'no-cors' blocks response parsing: When you use this mode, the browser restricts access to the response content. Calling response.json() will fail because the response is "opaque"—you can't read its body at all.
  • Incorrect request format for the Mailchimp API: The list-manage endpoint you're using expects data in application/x-www-form-urlencoded format (not JSON), and the email parameter must be named EMAIL (not the email you're using).
  • Flawed email validation: if (this.state.email > 3) is a broken check—you're comparing a string to a number, which won't properly validate if the email is valid or even non-empty.

Corrected Component Code

import React from "react";

class SubscribeOffer extends React.Component {
  constructor() {
    super();
    this.state = { email: "" };
  }

  fillEmailToSubscribe = (event) => {
    this.setState({ email: event.target.value });
  };

  // Helper to validate proper email format
  isValidEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  submitEmailToSubscribe = () => {
    const { email } = this.state;

    // Validate email first before sending request
    if (!this.isValidEmail(email)) {
      alert("Please enter a valid email address!");
      return;
    }

    // Encode data in the format Mailchimp expects
    const formData = new URLSearchParams();
    formData.append("EMAIL", email);
    // Add any other required fields from your Mailchimp list here (like FNAME if you've set it up)

    fetch('https://(myuser).list-manage.com/subscribe/post?u=(somenumber)&id=(myid)', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: formData.toString(),
    })
    .then((response) => {
      // Check if the request was successful
      if (response.ok) {
        alert('Thank you for subscribing!');
        this.setState({ email: "" }); // Clear input after successful subscription
      } else {
        alert('Oops, something went wrong. Please try again later.');
      }
    })
    .catch((error) => {
      console.error('Subscription error:', error);
      alert('Oops, something went wrong. Please try again later.');
    });
  };

  render() {
    return (
      <div>
        <h1>Get updated upcoming events in your inbox everyday!</h1>
        <p>Would you like us to send you updates about future events?</p>
        <input
          type='email'
          name='email-address'
          id='email-address'
          placeholder="your email"
          onChange={this.fillEmailToSubscribe}
          value={this.state.email}
          required
        />
        <button onClick={this.submitEmailToSubscribe}>Subscribe</button>
      </div>
    );
  }
}

export default SubscribeOffer;

What Changed & Why

  1. Removed mode: 'no-cors': This lets us read the API response properly. If you hit CORS issues later, you'll need to use a proxy server or confirm your Mailchimp list is configured to accept requests from your domain.
  2. Switched to application/x-www-form-urlencoded: Mailchimp's subscription endpoint requires this format, so we use URLSearchParams to encode the data correctly and set the matching header.
  3. Added proper email validation: The isValidEmail helper uses a regex to check for a valid email structure, which is way more reliable than a length-based check.
  4. Improved error handling: We now catch fetch errors and check the response status, so we can show meaningful alerts instead of letting the error go unhandled.
  5. Made the input a controlled component: Added value={this.state.email} to ensure the input always matches the component's state.

Extra Tips

  • Don't forget to replace (myuser), (somenumber), and (myid) in the fetch URL with your actual Mailchimp list details.
  • If you still run into CORS problems, consider setting up a simple proxy server (like using http-proxy-middleware with Create React App) to forward requests to the Mailchimp endpoint.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:51:32