Iran won their first match at a World Cup finals since 1998 as Morocco substitute Aziz Bouhaddouz scored an own goal in injury time.
Bouhaddouz put the ball into his own net with a diving header at the near post in the 95th minute as Morocco defended a left-wing free-kick.
The result was harsh on the African side, who had wasted numerous chances in the first half and were denied late on when Iran goalkeeper Alireza Beiranvand produced a fine save from Hakim Ziyech.
It was heart-breaking for Morocco, making their first finals appearance for 20 years, but after starting brightly they will rue their cautious second-half display.
But Iran took the victory, only their second in World Cup history after a 2-1 win over the United States at France 1998.
Morocco became the second African side to concede a late winning goal in the World Cup on Friday, after Egypt lost 1-0 to Uruguay in Group A, thanks to a last-minute header from Jose Gimenez.