w7corp/easywechat · error · BadMethodCallException

Response is immutable.

Error message

Response is immutable.

What it means

Response implements ArrayAccess only for reading: offsetSet() unconditionally throws BadMethodCallException('Response is immutable.') because mutating the wrapper would desync it from the underlying HTTP response it delegates to. Writes via $response['key'] = $value always fail, regardless of key or value.

Source

Thrown at src/Kernel/HttpClient/Response.php:218

        return '';
    }

    public function offsetExists(mixed $offset): bool
    {
        return array_key_exists($offset, $this->toArray());
    }

    public function offsetGet(mixed $offset): mixed
    {
        return $this->toArray()[$offset] ?? null;
    }

    /**
     * @throws BadMethodCallException
     */
    public function offsetSet(mixed $offset, mixed $value): void
    {
        throw new BadMethodCallException('Response is immutable.');
    }

    /**
     * @throws BadMethodCallException
     */
    public function offsetUnset(mixed $offset): void
    {
        throw new BadMethodCallException('Response is immutable.');
    }

    /**
     * @param  array<array-key, mixed>  $arguments
     */
    public function __call(string $name, array $arguments): mixed
    {
        return $this->response->{$name}(...$arguments);
    }

View on GitHub (pinned to f0cf0a8b83)

Solutions

  1. Materialize a local array first: $data = $response->toArray(); then mutate $data freely
  2. If a helper must accept both, branch on is_array() before writing

Example fix

// before
$response = $api->get('/cgi-bin/user/info');
$response['extra'] = 'computed'; // BadMethodCallException

// after
$data = $response->toArray();
$data['extra'] = 'computed';
Defensive patterns

Strategy: validation

Validate before calling

// Copy into a plain array before any mutation
$data = $response->toArray(); // mutable copy
$data['extra'] = 'value'; // safe

Type guard

function asMutableArray(\EasyWeChat\Kernel\HttpClient\Response $response): array
{
    return $response->toArray();
}

Prevention

When it happens

Trigger: Treating the response like a mutable array after reading it: $response['errcode'] = 0; or merging defaults by direct assignment.

Common situations: Copy-pasting array-manipulation code that targeted the toArray() output onto the response object itself, generic array helpers applied to an ArrayAccess object.

Related errors


AI-assisted analysis of w7corp/easywechat@f0cf0a8b83 (2026-08-21). Data as JSON: /api/errors/004f0542eb5c970f. Report an issue: GitHub.