diff --git a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php
index 3babf42..ae9628d 100644
--- a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php
+++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php
@@ -189,8 +189,11 @@ public function setValue($values, $notify = TRUE) {
         $entity_id = $this->get('entity')->getTargetIdentifier();
         // If the entity has been saved and we're trying to set both the
         // target_id and the entity values with a non-null target ID, then the
-        // value for target_id should match the ID of the entity value.
-        if (!$this->entity->isNew() && $values['target_id'] !== NULL && ($entity_id !== $values['target_id'])) {
+        // value for target_id should match the ID of the entity value. The
+        // entity ID as returned by $entity->id() might be a string, but the
+        // provided target_id might be an integer - therefore we have to do a
+        // non-strict comparison.
+        if (!$this->entity->isNew() && $values['target_id'] !== NULL && ($entity_id != $values['target_id'])) {
           throw new \InvalidArgumentException('The target id and entity passed to the entity reference item do not match.');
         }
       }
diff --git a/core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php b/core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php
index 90d4d1f..d9052cd 100644
--- a/core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php
+++ b/core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceItemTest.php
@@ -183,6 +183,15 @@ public function testContentEntityReferenceItem() {
     $entity->field_test_taxonomy_term->generateSampleItems();
     $entity->field_test_taxonomy_vocabulary->generateSampleItems();
     $this->entityValidateAndSave($entity);
+
+    // Tests that setting an integer target ID together with an entity object
+    // succeeds and does not cause any exceptions. There is no assertion here,
+    // as the assignment should not throw any exceptions and if it does the
+    // test will fail.
+    // @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue().
+    $user = User::create(['name' => $this->randomString()]);
+    $user->save();
+    $entity = EntityTest::create(['user_id' => ['target_id' => (int) $user->id(), 'entity' => $user]]);
   }
 
   /**
